<?php

namespace app\admin\controller;

use app\admin\model\ProjectYearSwitch;
use app\common\controller\Backend;
use app\admin\model\Fields;
use app\admin\model\Admin;
use app\admin\model\AdminProject;
use think\Db;
use fast\Random;
use app\admin\library\Time;
use think\Config;

use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $chargeDepsArr = [];
    protected $fiveindustryArr = [];
    protected $industrycategoryArr = [];
    protected $realmArr = [];
    protected $carrierArr = [];
    protected $tradecategoryArr = [];
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project();
        $this->progress = new \app\admin\model\ProjectProgress();
        $this->plan = new \app\admin\model\ProjectPlan();
        $this->stage = new  \app\admin\model\ProjectStage();
        $this->investment = new  \app\admin\model\ProjectInvestment();
        $this->contacts = new  \app\admin\model\ProjectContacts();
        $this->central = new  \app\admin\model\Centraloffice();
        $this->attribute = new  \app\admin\model\InvestorAttribute();

        $this->centralcontact = new  \app\admin\model\ProjectCentralcontact();

        $groupIds = $this->auth->getGroupIds();
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());        
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());


        $this->hasWhereTabel = 'stages';
        $this->hasWhereArr = [];
        // $this->relationtTable = 'stages';

        // 主责部门
        $this->chargeDepsArr = \app\admin\model\Chargedep::order('sort asc,id asc')->column('id,name');
        $this->assign('chargeDepsArr',$this->chargeDepsArr);

        // 协办部门
        // $this -> assign('streets',['-100'=>'待定']+getSelectList('chargedep',['group_id' => 5]));
        $this->assign('assistArr',$this->chargeDepsArr);

        // 落户街道
        $option_where = [];
        $option_where['group_id'] = 5;
        $settle_street = getSelectList('chargedep', $option_where);
        $this->assign('settle_street',['-100'=>'待定']+$settle_street);

        // 产业类别
        $this->industrycategoryArr = \app\admin\model\IndustryCategory::column('id,name');
        $this->assign('industrycategoryArr',$this->industrycategoryArr);

        // 产业领域
        $this->realmArr = \app\admin\model\Realm::column('id,name');
        $this->assign('realmArr',$this->realmArr);

        // 五大产业
        $this->fiveindustryArr = \app\admin\model\FiveIndustry::column('id,name');
        $this->assign('fiveindustry',$this->fiveindustryArr);

        // 载体情况
        $carrier_where = [];
        $this->carrierArr = getSelectList('carrier', $carrier_where);
        $this->assign('carrierArr',$this->carrierArr);

        // 项目类别
        $w_act= "";
        $activityArr = \app\admin\model\Activity::where($w_act)->order('weigh desc')->select();
         
        // $activityArr = \app\admin\model\Activity::all();
        $activity = [];
        foreach ($activityArr as $dep){
            // $activity[$dep -> id] = $dep->year.$dep -> name;
            $activity[$dep -> id] = $dep -> name;
        }
        $this -> assign('activity',$activity);

        // 行业类别
        $this->tradecategoryArr = \app\admin\model\TradeCategory::all();
        $tradecategory = [];
        foreach ($this->tradecategoryArr as $tr){
            $tradecategory[$tr -> id] =$tr -> name;
        }
        $this->assign('tradecategory',$tradecategory);

        // 科室
        $centraloffices = \app\admin\model\Centraloffice::column('id,name');
        $this -> assign('centraloffices',[''=>'请选择']+$centraloffices);

        // 分管区领导
        $leaders = \app\admin\model\Leaders::order('sort')->column('id,name');
        $this -> assign('leaders',$leaders);

        // 接洽领导
        $contact_leaders = \app\admin\model\ContactLeaders::column('id,name');
        $this -> assign('leaders_list',[''=>'无']+$contact_leaders);

        // 投资方性质
        $this -> assign('attribute',getSelectList('investor_attribute'));

        $this -> assignConfig('attribute',getSelectList('investor_attribute'));

        $this -> assign('countries',[''=>'请选择']+config('app.different_countries'));

        $this -> assignConfig('different_countries',config('app.different_countries'));


        $this->project_tablename = 'nsig_project_new';

        $year = [];
        for ($i=2020; $i <=date('Y') ; $i++) { 
            $year[] = $i;
        }
        $this -> assign('year',$year);

        // 国别追加
        $area_option = '<option value="">请选择</option>';
        foreach (config('app.different_countries') as $k => $v) {
           $area_option .='<option value="'.$k.'">'.$v.'</option>';
        }
        $this -> assignConfig('area_option',$area_option);

        // 投资方性质追加
        $attribute_option = '';
        foreach (getSelectList('investor_attribute') as $k1 => $v1) {
           $attribute_option .='<option value="'.$k1.'">'.$v1.'</option>';
        }
        $this -> assignConfig('attribute_option',$attribute_option);

        // 协办单位追加
        $assist_option = '<option value="">请选择</option>';
        foreach ($this->chargeDepsArr as $k2 => $v2) {
           $assist_option .='<option value="'.$k2.'">'.$v2.'</option>';
        }
        $this -> assignConfig('assist_option',$assist_option);

        $this -> assignConfig('groupIds',$groupIds[0]);
        $this -> assign('groupIds',$groupIds[0]);

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    public function __baselist($data =array())
    {
        $where_delete = 'p.is_delete=0';
        if($data['action']=='index')
        {
            $where_delete = $where_delete.' and p.progress_status_id<9 ';
        }else if($data['action']=='discuss'){
            $where_delete = $where_delete.' and p.progress_status_id=1 ';
        }else if($data['action']=='new_land'){
            $where_delete = $where_delete.' and p.carrier_id=1 and p.progress_status_id<9 ';
        }else if($data['action']=='centralcontact'){
            $where_delete = $where_delete.' and p.progress_status_id<9 ';
        }else if($data['action']=='signed'){
            if($data['typeid']==1)
            {
                $where_delete = $where_delete.' and p.progress_status_id<9 and p.asset_type_id in(2,3)';
            }else if($data['typeid']==2){
                $where_delete = $where_delete.' and p.progress_status_id<9 and p.asset_type_id=1';
            }else if($data['typeid']==3){
                $where_delete = $where_delete.' and p.progress_status_id<9';
            }else if($data['typeid']==4){
                $where_delete = $where_delete.' and p.progress_status_id<9';
            }
        }
        $groupIds = $this->auth->getGroupIds();
        $showAna = true;
        if(in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $where_delete .= " and (p.chargedep_ids IN (".$chargedep_id.") or p.assist_ids IN (".$chargedep_id.") )";
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            if($data['action']=='new_land'){
                $where_search='s.project_stage_id IN (4,5) and s.project_stage_time<'.strtotime('2022-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2022-01-01');
            }else if($data['action']=='centralcontact'){
                // $where_search = "c.leader_ids IN (".$data['leader'].") ";
                $where_search = "FIND_IN_SET(".$data['leader'].",c.leader_ids) ";
            }else if($data['action']=='signed'){
                if($data['typeid']==1)
                {
                    $where_search = ' s.project_stage_id IN (4,5) and  s.project_stage_time<'.strtotime('2022-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2022-01-01');
                }else if($data['typeid']==2){
                    $where_search = ' s.project_stage_id IN (4,5) and  s.project_stage_time<'.strtotime('2022-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2022-01-01');
                }else if($data['typeid']==3){
                    $where_search = ' s.project_stage_id =5 and s.project_stage_time<'.strtotime('2022-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2022-01-01');
                }else if($data['typeid']==4){
                    $where_search = ' s.project_stage_id =4 and s.project_stage_time<'.strtotime('2022-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2022-01-01');
                }
            }else{
                $where_search = '';
            }

            // 跟进时间是单独写的 filterextra
            $filter = $this->request->get("filterextra", '');
            $filter = (array)json_decode($filter, true);

            // 显示暂缓和终止
            if(!empty($filter['progress_statusid']))
            {
                $progress_statusid = $filter['progress_statusid'];
                if($progress_statusid==1){
                    $where_delete = " p.is_delete=0";
                }
            }
            if(!empty($filter['project_stage_time']))
            {
                $project_stage_time = $filter['project_stage_time'];
                $dispatchTimeArr = explode(' - ',$project_stage_time);
                $dispatchtimeBetween = [strtotime(trim($dispatchTimeArr[0])),strtotime(trim($dispatchTimeArr[1]))];
                if(!empty($where_search))
                    $where_search .= " and s.project_stage_time >= ".strtotime(trim($dispatchTimeArr[0]))." and s.project_stage_time <= ".strtotime(trim($dispatchTimeArr[1]))." and s.project_stage_time>0";
                else
                    $where_search .= " s.project_stage_time >= ".strtotime(trim($dispatchTimeArr[0]))." and s.project_stage_time <=".strtotime(trim($dispatchTimeArr[1]))." and s.project_stage_time>0";
            }
            if(!empty($filter['project_stage_id']))
            {
                $project_stage_id = $filter['project_stage_id'];
                if($project_stage_id===1)
                {
                    if(!empty($where_search))
                        $where_search .= " and p.progress_status_id = ".$project_stage_id;
                    else
                        $where_search .= " p.progress_status_id = ".$project_stage_id;
                }else{
                    if(!empty($where_search))
                        $where_search .= " and s.project_stage_id IN (".$project_stage_id.")";
                    else
                        $where_search .= " s.project_stage_id IN (".$project_stage_id.")";
                }
            }

            // 多选项目类别
            if(!empty($filter['project_source_ids']))
            {
                $project_source_ids = $filter['project_source_ids'];
                $arr = explode(',', $project_source_ids);
                $str = "(";
                foreach ($arr as $key => $va){
                    $str .= " FIND_IN_SET(".$va.",p.project_source_ids) or ";
                }
                $str = substr($str,0,-3);
                $str .= ")";
                $where_delete .= " and ".$str;
            }

            if(!empty($filter['trade_category_ids']))
            {
                $trade_category_ids = $filter['trade_category_ids'];
                $arr = explode(',', $trade_category_ids);
                $str = "(";
                foreach ($arr as $key => $va){
                    $str .= " FIND_IN_SET(".$va.",p.trade_category_ids) or ";
                }
                $str = substr($str,0,-3);
                $str .= ")";
                $where_delete .= " and ".$str;
            }


            // 多选区领导接洽
            if(!empty($filter['leader_ids']))
            {
                $leader_ids = $filter['leader_ids'];
                $arr = explode(',', $leader_ids);
                $str = "(";
                foreach ($arr as $key => $va){
                    $str .= " FIND_IN_SET(".$va.",c.leader_ids) or ";
                }
                $str = substr($str,0,-3);
                $str .= ")";
                $where_delete .= " and ".$str;
                // $where_delete .= " and c.leader_ids IN (".$leader_ids.")";
            } 
            // 多选接洽科室
            if(!empty($filter['centraloffice_id']))
            {
                $leader_ids = $filter['centraloffice_id'];
                $arr = explode(',', $leader_ids);
                $str = "(";
                foreach ($arr as $key => $va){
                    $str .= " FIND_IN_SET(".$va.",c.centraloffice_id) or ";
                }
                $str = substr($str,0,-3);
                $str .= ")";
                $where_delete .= " and ".$str;
            } 

            if(!empty($filter['contact_typeid']))
            {
                $contact_typeid = $filter['contact_typeid'];
                $where_delete .= " and c.contact_typeid = ".$contact_typeid;
            } 
            //接洽时间
            if(!empty($filter['receive_time']))
            {
                $receive_time = $filter['receive_time'];
                $dispatchTimeArr = explode(' - ',$receive_time);
                $dispatchtimeBetween = [strtotime(trim($dispatchTimeArr[0])),strtotime(trim($dispatchTimeArr[1]))];
                if(!empty($where_search))
                        $where_search .= " and c.receive_time >= ".strtotime(trim($dispatchTimeArr[0]))." and c.receive_time <=".strtotime(trim($dispatchTimeArr[1]))." and c.receive_time>0";
                    else
                        $where_search .= " c.receive_time >= ".strtotime(trim($dispatchTimeArr[0]))." and c.receive_time <=".strtotime(trim($dispatchTimeArr[1]))." and c.receive_time>0";

                
            }
            // 投资方名称
            if(!empty($filter['investment_name']))
            {
                $investment_name = $filter['investment_name'];
                $str = " i.investment_name LIKE '%".$investment_name."%'";
                $where_delete .= " and ".$str;
            }

            // 投资方地区
            if(!empty($filter['investment_area']))
            {
                $investment_area = $filter['investment_area'];
                $str = " i.investment_area LIKE '%".$investment_area."%'";
                $where_delete .= " and ".$str;
            }

            // // 投资方国别
            if(!empty($filter['investment_country']))
            {
                $investment_country = $filter['investment_country'];
                $str = " i.investment_code = '".$investment_country."'";
                $where_delete .= " and ".$str;
            }

            // 投资方性质
            if(!empty($filter['investment_attribute_ids']))
            {
                $investment_attribute_ids = $filter['investment_attribute_ids'];
                $arr = explode(',', $investment_attribute_ids);
                $str = "(";
                foreach ($arr as $key => $va){
                    $str .= " FIND_IN_SET(".$va.",i.investment_attribute_ids) or ";
                }
                $str = substr($str,0,-3);
                $str .= ")";
                $where_delete .= " and ".$str;
            }

            // 领导角色排序调整
            if(in_array(GROUP_LEADER,$groupIds))
                $exp = new \think\db\Expression('field(p.progress_status_id,5,4,3,6,7,8,2,1)');
            else
                $exp = new \think\db\Expression('field(p.status,0,-1,1,2,3)');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->alias('p')
                ->join('project_stage s','p.id=s.project_id','left')
                ->join('project_centralcontact c','p.id=c.project_id','left')
                ->join('project_investment i','p.id=i.project_id','left')
                ->where($where)
                ->where($where_search)
                ->where($where_delete)
                ->where($this->whereExtend)
                ->order($exp)
                ->order($sort, $order)
                ->group('p.name')
                ->count();
            $list = $this->model->alias('p')
                ->join('project_stage s','p.id=s.project_id','left')
                ->join('project_centralcontact c','p.id=c.project_id','left')
                ->join('project_investment i','p.id=i.project_id','left')
                ->field('p.*,s.project_id,s.project_stage_time,c.leader_ids,c.leader_names,c.receive_time,c.receive_time_desc,c.contact_typeid')
                ->where($where)
                ->where($where_search)
                ->where($where_delete)
                ->order($exp)
                ->where($this->whereExtend)
                ->order($this->sortExtend)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->group('p.name')
                ->select();

            // echo $this->model->getLastSql();
            // exit();
            if($data['action']=='index')
            {
                if(isset($list))
                {
                    foreach($list as $key => $value)
                    {
                        $plan_time = $this->plan->where(['project_id'=>$value['id'],'is_standard'=>0])->min('plan_time');
                        $list[$key]['plan_time'] = $plan_time ? $plan_time : "" ;
                        $list[$key]['local_time'] = time();
                    }
                }    
                $update_total = $this->model->alias('p')
                    ->join('project_stage s','p.id=s.project_id','left')
                    ->join('project_centralcontact c','p.id=c.project_id','left')
                    ->join('project_investment i','p.id=i.project_id','left')
                    ->where($where)
                    ->where($where_search)
                    ->where($where_delete)
                    ->where('p.status=1')
                    ->where($this->whereExtend)
                    ->order($sort, $order)
                    ->group('p.name')
                    ->count();
                if($update_total>0)    
                    $percent = number_format($update_total/$total*100)."%";
                else
                    $percent = 0;

                $sum = array('update_total'=>$update_total,'total'=>$total,'percent'=>$percent);

                $list = collection($list)->toArray();
                $result = array("total" => $total, "rows" => $list,"extend" =>$sum);
            }else{
                $list = collection($list)->toArray();
                $result = array("total" => $total, "rows" => $list);
            }
            return json($result);
        }
        $this->assignConfig('is_stop',$data['is_stop']);//是否显示暂缓终止
        $this->assign('leader',$data['leader']);
        $this->assignconfig('leader',$data['leader']);
        $this->assign('typeid',$data['typeid']);
        $this->assignconfig('typeid',$data['typeid']);
        return $this->view->fetch();
    }

    /**
     * [index description]
     * @return [type] [description]
     */
    public function index()
    {
        $data = [
            'action'=>'index',
            'is_stop'=>1,
            'leader'=>0,
            'typeid'=>0
        ];
        return self::__baselist($data);
    }

    /**
     * [discuss description]
     * @return [type] [description]
     */
    // 在谈项目
    public function discuss()
    {
        $data = [
            'action'=>'discuss',
            'is_stop'=>0,
            'leader'=>0,
            'typeid'=>0
        ];
        return self::__baselist($data);
    }

    /**
     * [discuss description]
     * @return [type] [description]
     */
    // 新征地项目
    public function new_land()
    {
        $data = [
            'action'=>'new_land',
            'is_stop'=>0,
            'leader'=>0,
            'typeid'=>0
        ];
        return self::__baselist($data);
    }


    // 中心接洽\外出考察项目
    public function centralcontact($leader = NULL)
    {
        $data = [
            'action'=>'centralcontact',
            'is_stop'=>0,
            'leader'=>$leader,
            'typeid'=>0
        ];
        return self::__baselist($data);
    }

    // 2021年签约项目
    public function signed($typeid = NULL)
    {
        $data = [
            'action'=>'signed',
            'is_stop'=>0,
            'leader'=>0,
            'typeid'=>$typeid
        ];
        return self::__baselist($data);
    }

    /**
     * [add description]
     */
    public function add()
    {
        if($this->request->isPost())
        {   
            
            $project_id = $this -> request -> post('project_id');
            if($project_id==0)
            {
                $data = $this -> request -> post('row/a');
                if(!empty($data['name'])){
                    $exist_row = $this->model->where(['name'=>$data['name'],'is_delete'=>0])->find();
                    if($exist_row)
                        $this->error(__("此项目已存在"));
                }
                $data['pno'] = Random::uuid();
                $data['progress_status_id'] = 0;
                $ret = $this->model-> save($data);
                if($ret){
                    return $this -> success($this->model->id);
                }
            }else{

                $current = $this -> request -> post('current');
                $row = $this->model->get($project_id);
                if($current==1)
                {
                    $ment = $this -> request -> post('investment/a');
                    $insert = [];
                    for ($i=0; $i < count($ment['investment_name']) ; $i++)
                    { 
                        $insert[$i]['project_id'] = $project_id;
                        $insert[$i]['project_name'] = $row->name;
                        $insert[$i]['investment_name'] = $ment['investment_name'][$i];
                        $insert[$i]['investment_area'] = $ment['investment_area'][$i];

                        $insert[$i]['investment_code'] = $ment['investment_code'][$i];
                        $insert[$i]['investment_country'] = config('app.different_countries')[$ment['investment_code'][$i]] ?? '';

                        // $insert[$i]['investment_country'] = $ment['investment_country'][$i];
                        $investment_attribute_ids = '';
                        $investment_attribute_names = '';
                        if(isset($ment['investment_attribute_ids'][$i]))
                        {
                            foreach($ment['investment_attribute_ids'][$i] as $key => $v)
                            {
                                $chargedep = $this->attribute->where(['id'=>$v])->find();
                                $investment_attribute_ids .= $v.",";
                                $investment_attribute_names .= $chargedep['name'].",";
                            }
                            $investment_attribute_ids = substr($investment_attribute_ids,0,strlen($investment_attribute_ids)-1);
                            $investment_attribute_names = substr($investment_attribute_names,0,strlen($investment_attribute_names)-1);
                            $insert[$i]['investment_attribute_ids'] = $investment_attribute_ids;
                            $insert[$i]['investment_attribute_names'] = $investment_attribute_names;
                        }
                    }
                    // echo "<pre>";
                    // var_dump($insert);
                    // exit();
                    $ret = $this->investment->saveAll($insert);
                    $info = $this->investment->where(['project_id'=>$project_id])->order('id desc')->find();
                    if(isset($info)){
                        $row->investment_name = $info['investment_name'];
                        $row->investment_area = $info['investment_area'];
                        $row->investment_country = $info['investment_country'];
                        $row->investment_attribute_ids = $info['investment_attribute_ids'];
                        $row->investment_attribute_names = $info['investment_attribute_names'];
                        $row->save();                        
                    }
                    return $this -> success($project_id);
                }

                if($current==2)
                {
                    $contacts = $this -> request -> post('contacts/a');
                    $insert = [];
                    for ($i=0; $i < count($contacts['assist_id']) ; $i++)
                    { 

                        if($contacts['assist_id'][$i]>0)
                        {
                            $insert[$i]['project_id'] = $project_id;
                            $insert[$i]['project_name'] = $row->name;
                            $insert[$i]['assist_id'] = $contacts['assist_id'][$i];
                            $office = (new \app\admin\model\Chargedep)->where(['id'=>$contacts['assist_id'][$i]])->find();
                            $insert[$i]['assist_name'] = $office['name'];

                            $insert[$i]['assist_duty'] = $contacts['assist_duty'][$i];
                            $insert[$i]['assist_nickname'] = $contacts['assist_nickname'][$i];
                            $insert[$i]['assist_tel'] = $contacts['assist_tel'][$i];

                        }
                    }

                    $params = $this -> request -> post('row/a');
                    if(isset($params['organizer_departid']))
                    {
                        $chargedep = (new \app\admin\model\Chargedep)->where(['id'=>$params['organizer_departid']])->find();
                        $params['organizer_depart'] = $chargedep['name'];
                    }
                    if(isset($params['socialized_department_id']))
                    {
                        $office = (new \app\admin\model\Centraloffice)->where(['id'=>$params['socialized_department_id']])->find();
                        $params['socialized_department'] = $office['name'];
                    } 
                    if(!$this->auth->isSuperAdmin()){
                        $params['status'] = 0;
                    }else{
                        $params['status'] = 1;
                    }
                    $params['progress_status_id'] = 0;
                    $res = $row->save($params);
                    if(!empty($insert))
                        $this->contacts->saveAll($insert);
                    
                    return $this -> success($project_id);
                }
            }
        }
        $this->assignconfig('ids',0);
        $this->assignconfig('status',-1);
        return $this->view->fetch();
    }


    /**
     * [checkedit description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function checkedit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row_stage = $this->stage->where(['project_id'=>$ids,'status'=>0])->select();
        $this->assign("row_stage", $row_stage);

        $row_progress = $this->progress->where(['project_id'=>$ids,'status'=>0])->select();
        $this->assign("row_progress", $row_progress);

        $row_plan = $this->plan->where(['project_id'=>$ids,'status'=>0])->select();
        if(!empty($row_plan)&&is_array($row_plan))
        {
            foreach($row_plan as $key => $value)
            {
                $row_plan[$key]['status_name'] = Config::get('app.project_plan_status')[$value['plan_status']] ?? '';
            }
        }
        $this->assign("row_plan", $row_plan);

        $row_centralcontact = $this->centralcontact->where(['project_id'=>$ids,'status'=>0])->select();
        $this->assign("row_centralcontact", $row_centralcontact);

        $this->assign("row", $row);
        $this->assignconfig("ids", $ids);
        return $this->view->fetch();
    }

    /**
     * [rejectmemo description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function rejectmemo($ids = null)
    {
        $this->whereExtend['is_delete'] = 0;
        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();
            if(!$chargedep_data)
                $this->error('您还未绑定部门或街道');

            $chargedep_id = $chargedep_data->chargedep_id;
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
        }
        $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['reject_memo_status'] = 1;
            $params['status'] = 2;
            $result = false;
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {

                $update = [];
                $update['status']= 2;
                $stage_list = $this->stage->where(['project_id'=>$ids,'progress_status_id'=>$row->progress_status_id,'status'=>0])->select();
                if(!empty($stage_list)&&is_array($stage_list))
                {
                    foreach ($stage_list as $key => $val) 
                    {
                        $this->stage->where(['id'=>$val['id']])->update($update);
                    }
                } 
    
                $progress_list = $this->progress->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($progress_list)&&is_array($progress_list))
                {
                    foreach ($progress_list as $k => $v) 
                    {
                        $this->progress->where(['id'=>$v['id']])->update($update);
                    }
                } 

                $plan_list = $this->plan->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($plan_list)&&is_array($plan_list))
                {
                    foreach ($plan_list as $y => $va) 
                    {
                        $this->plan->where(['id'=>$va['id']])->update($update);
                    }
                } 
                $centralcontact_list = $this->centralcontact->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($centralcontact_list)&&is_array($centralcontact_list))
                {
                    foreach ($centralcontact_list as $y => $va) 
                    {
                        $this->centralcontact->where(['id'=>$va['id']])->update($update);
                    }
                }

                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }


    /**
     * [checkpass_all description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function checkpass_all($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $data = [];
            $data['status'] = 1;
            $data['update_status'] = 0;
            $data['is_noprogress'] = 1;
            $data['is_new'] = 0;
            $result = $row->allowField(true)->save($data);
            if ($result !== false) {

                $update = [];
                $update['status']= 1;
                $stage_list = $this->stage->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($stage_list)&&is_array($stage_list))
                {
                    foreach ($stage_list as $key => $val) 
                    {
                        $this->stage->where(['id'=>$val['id']])->update($update);
                    }
                } 
    
                $progress_list = $this->progress->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($progress_list)&&is_array($progress_list))
                {
                    foreach ($progress_list as $k => $v) 
                    {
                        $this->progress->where(['id'=>$v['id']])->update($update);
                    }
                } 

                $plan_list = $this->plan->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($plan_list)&&is_array($plan_list))
                {
                    foreach ($plan_list as $y => $va) 
                    {
                        $this->plan->where(['id'=>$va['id']])->update($update);
                    }
                } 

                $centralcontact_list = $this->centralcontact->where(['project_id'=>$ids,'status'=>0])->select();
                if(!empty($centralcontact_list)&&is_array($centralcontact_list))
                {
                    foreach ($centralcontact_list as $y => $va) 
                    {
                        $this->centralcontact->where(['id'=>$va['id']])->update($update);
                    }
                }

                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
    }



    // 编辑
    public function update($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost())
        {
            $params = $this -> request -> post('row/a');
            $type = $this -> request -> post('type/a');

            if(isset($params['chargedep_ids']))
            {
                $settle_street = (new \app\admin\model\Chargedep)->where(['id'=>$params['chargedep_ids']])->find();
                $params['chargedep_names'] = $settle_street['name'];
            }  
            

            $assist_ids = '';
            $assist_names = '';
            if(isset($params['assist_ids']))
            {
                foreach($params['assist_ids'] as $key => $v)
                {
                    $chargedep = (new \app\admin\model\Chargedep)->where(['id'=>$v])->find();
                    $assist_ids .= $v.",";
                    $assist_names .= $chargedep['name'].",";
                }
                $assist_ids = substr($assist_ids,0,strlen($assist_ids)-1);
                $assist_names = substr($assist_names,0,strlen($assist_names)-1);
                $params['assist_ids'] = $assist_ids;
                $params['assist_names'] = $assist_names;
            }

            $source_ids = '';
            $source_names = '';
            if(isset($params['project_source_ids']))
            {
                foreach($params['project_source_ids'] as $key => $v)
                {
                    $chargedep = (new \app\admin\model\Activity)->where(['id'=>$v])->find();
                    $source_ids .= $v.",";
                    $source_names .= $chargedep['name'].",";
                }
                $source_ids = substr($source_ids,0,strlen($source_ids)-1);
                $source_names = substr($source_names,0,strlen($source_names)-1);
                $params['project_source_ids'] = $source_ids;
                $params['project_source_names'] = $source_names;
            } 
            $settle_street_ids = '';
            $settle_street_names = '';
            if(isset($params['settle_street_ids']))
            {
                foreach($params['settle_street_ids'] as $key => $v)
                {
                    $chargedep = (new \app\admin\model\Chargedep)->where(['id'=>$v])->find();
                    $settle_street_ids .= $v.",";
                    $settle_street_names .= $chargedep['name'].",";
                }
                $settle_street_ids = substr($settle_street_ids,0,strlen($settle_street_ids)-1);
                $settle_street_names = substr($settle_street_names,0,strlen($settle_street_names)-1);
                $params['settle_street_ids'] = $settle_street_ids;
                $params['settle_street_names'] = $settle_street_names;
            }


            if(isset($params['industry_category_id']))
            {
                $industrycategory = (new \app\admin\model\IndustryCategory)->where(['id'=>$params['industry_category_id']])->find();
                $params['industry_category_name'] = $industrycategory['name'];
            }  

            if(isset($params['industry_realm_id']))
            {
                $realm = (new \app\admin\model\Realm)->where(['id'=>$params['industry_realm_id']])->find();
                $params['industry_realm_name'] = $realm['name'];
            }  

            if(isset($params['five_industry_id']))
            {
                $fiveindustry = (new \app\admin\model\FiveIndustry)->where(['id'=>$params['five_industry_id']])->find();
                $params['five_industry_name'] = $fiveindustry['name'];
            }  
            $trade_category_ids = '';
            $trade_category_names = '';
            if(isset($params['trade_category_ids']))
            {
                foreach($params['trade_category_ids'] as $key => $v)
                {
                    $chargedep = (new \app\admin\model\TradeCategory)->where(['id'=>$v])->find();
                    $trade_category_ids .= $v.",";
                    $trade_category_names .= $chargedep['name'].",";
                }
                $trade_category_ids = substr($trade_category_ids,0,strlen($trade_category_ids)-1);
                $trade_category_names = substr($trade_category_names,0,strlen($trade_category_names)-1);
                $params['trade_category_ids'] = $trade_category_ids;
                $params['trade_category_names'] = $trade_category_names;
            }

            if(isset($params['asset_type_id']))
            {
                $params['asset_type_name'] = config('app.asset_type_id')[$params['asset_type_id']] ?? '';
            }
            if(isset($params['carrier_id']))
            {
                $carrier = $trade_category = (new \app\admin\model\Carrier)->where(['id'=>$params['carrier_id']])->find();
                $params['carrier_name'] = $carrier['name'];
            }
            if(isset($params['organizer_departid']))
            {
                $chargedep = (new \app\admin\model\Chargedep)->where(['id'=>$params['organizer_departid']])->find();
                $params['organizer_depart'] = $chargedep['name'];
            }
            if(isset($params['branch_leader_id'])){
                $leader = (new \app\admin\model\Leaders())->whereIn('id', $params['branch_leader_id'])->find();
                $params['branch_leader_name'] = $leader['name'];
            }
            if(isset($params['socialized_department_id']))
            {
                $office = (new \app\admin\model\Centraloffice)->where(['id'=>$params['socialized_department_id']])->find();
                $params['socialized_department'] = $office['name'];
            } 
            $leader_ids = '';
            $leader_names = '';
            if(isset($params['leader_ids']))
            {
                foreach($params['leader_ids'] as $key => $v)
                {
                    $chargedep = (new \app\admin\model\ContactLeaders)->where(['id'=>$v])->find();
                    $leader_ids .= $v.",";
                    $leader_names .= $chargedep['name'].",";
                }
                $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1);
                $leader_names = substr($leader_names,0,strlen($leader_names)-1);
                $params['leader_ids'] = $leader_ids;
                $params['leader_names'] = $leader_names;
            }
            // $type = $this -> request -> post('type/a');
            if($type['typeid']==0) //0表示提交
            {
                if(!$this->auth->isSuperAdmin()){
                    $params['status'] = 0;
                }else{
                    $params['status'] = 1;
                    $params['update_status'] = 0; //已审核未更新
                } 
            }elseif($type['typeid']==1){ //1表示暂存
                $params['status'] = -1;
                $params['update_status'] = 1; //已更新
            }else{ //无进展确认
                $params['status'] = 1;
            }
            // 添加编辑，暂存记录的
            foreach($params as $key =>$value)
            {
                if($key !='status')
                {
                    $array_id = '';
                    if(is_array($value))
                    {
                        foreach($value as $k => $v)
                        {
                            $array_id .= $v.",";
                        }
                        $array_id = substr($array_id,0,strlen($array_id)-1);
                        if($row->$key != $array_id)
                            $this->addCheck($row->id, $key,$array_id);
                    }else{
                        if($row->$key != $value)
                            $this->addCheck($row->id, $key,$value);
                    }
                }
            }

            $row->allowField(true) -> save($params);

            $ment = $this -> request -> post('investment/a');
            $add = [];
            for ($i=0; $i < count($ment['investment_name']) ; $i++)
            { 
                $add[$i]['project_id'] = $row->id;
                $add[$i]['project_name'] = $row->name;
                $add[$i]['investment_name'] = $ment['investment_name'][$i];
                $add[$i]['investment_area'] = $ment['investment_area'][$i];
                $add[$i]['investment_code'] = $ment['investment_code'][$i];
                $add[$i]['investment_country'] = config('app.different_countries')[$ment['investment_code'][$i]] ?? '';

                $investment_attribute_ids = '';
                $investment_attribute_names = '';
                if(isset($ment['investment_attribute_ids'][$i]))
                {
                    foreach($ment['investment_attribute_ids'][$i] as $key => $v)
                    {
                        $chargedep = $this->attribute->where(['id'=>$v])->find();
                        $investment_attribute_ids .= $v.",";
                        $investment_attribute_names .= $chargedep['name'].",";
                    }
                    $investment_attribute_ids = substr($investment_attribute_ids,0,strlen($investment_attribute_ids)-1);
                    $investment_attribute_names = substr($investment_attribute_names,0,strlen($investment_attribute_names)-1);
                    $add[$i]['investment_attribute_ids'] = $investment_attribute_ids;
                    $add[$i]['investment_attribute_names'] = $investment_attribute_names;
                }
            }
            $ment_list = $this->investment->where(['project_id'=>$row->id])->select();
            if(!empty($ment_list)&&is_array($ment_list))
            {
                foreach ($ment_list as $key => $value) 
                {
                    $value->delete();
                }
            }

            $ret = $this->investment->saveAll($add);
            $info = $this->investment->where(['project_id'=>$row->id])->order('id desc')->find();
            if(isset($info)){
                $row->investment_name = $info['investment_name'];
                $row->investment_area = $info['investment_area'];
                $row->investment_country = $info['investment_country'];
                $row->investment_attribute_ids = $info['investment_attribute_ids'];
                $row->investment_attribute_names = $info['investment_attribute_names'];
                $row->save();                        
            }
            
            $contacts = $this -> request -> post('contacts/a');
            if($contacts)
            {
                $insert = [];
                for ($i=0; $i < count($contacts['assist_id']) ; $i++)
                { 
                    
                    if($contacts['assist_id'][$i]>0)
                    {
                        $insert[$i]['project_id'] = $row->id;
                        $insert[$i]['project_name'] = $row->name;
                        $insert[$i]['assist_id'] = $contacts['assist_id'][$i];
                        $office = (new \app\admin\model\Chargedep)->where(['id'=>$contacts['assist_id'][$i]])->find();
                        $insert[$i]['assist_name'] = $office['name'];
                        $insert[$i]['assist_duty'] = $contacts['assist_duty'][$i];
                        $insert[$i]['assist_nickname'] = $contacts['assist_nickname'][$i];
                        $insert[$i]['assist_tel'] = $contacts['assist_tel'][$i];
                    }
                    
                }
                $contacts_list = $this->contacts->where(['project_id'=>$row->id])->select();
                if(!empty($contacts_list)&&is_array($contacts_list))
                {
                    foreach ($contacts_list as $key => $val) 
                    {
                        $val->delete();
                    }
                }
                if(!empty($insert))
                    $this->contacts->saveAll($insert); 
            }
 
            // 项目阶段  推进详情 项目计划全部改成待审核
            $update = [];
            if($type['typeid']==0) //0表示提交
            {
                $update['status']= $this->auth->isSuperAdmin() ? 1 : 0;
            }else if($type['typeid']==1){
                $update['status']= -1;
            }else{
                $update['status']= 1;
            }
                
            // 待提交，或者 已驳回项目
            $project_where = '(status=-1 or status=2) and project_id='.$row->id;
            $stage_list = $this->stage->where($project_where)->select();
            if(!empty($stage_list)&&is_array($stage_list))
            {
                foreach ($stage_list as $key => $val) 
                {
                    $this->stage->where(['id'=>$val['id']])->update($update);
                }
            } 

            $progress_list = $this->progress->where($project_where)->select();
            if(!empty($progress_list)&&is_array($progress_list))
            {
                foreach ($progress_list as $k => $v) 
                {
                    $this->progress->where(['id'=>$v['id']])->update($update);
                }
            } 
            $plan_list = $this->plan->where($project_where)->select();
            if(!empty($plan_list)&&is_array($plan_list))
            {
                foreach ($plan_list as $y => $va) 
                {
                    $this->plan->where(['id'=>$va['id']])->update($update);
                }
            } 

            $centralcontact_list = $this->centralcontact->where($project_where)->select();
            if(!empty($centralcontact_list)&&is_array($centralcontact_list))
            {
                foreach ($centralcontact_list as $y => $va) 
                {
                    $this->centralcontact->where(['id'=>$va['id']])->update($update);
                }
            } 

            $this->success('操作成功');

        }  
        $activityarr = [];
        if(!empty($row->project_source_year))
        {
            $activityarr = (new \app\admin\model\Activity)->where(['year'=>$row->project_source_year])->select();
        }
        $this -> assign('activityarr',$activityarr);

        //投资方 
        $investment_list = $this->investment->where(['project_id' => $ids])->order('id')->select();

        // 协办单位
        $contact_list = $this->contacts->where(['project_id' => $ids])->order('id')->select();

        $this -> assign('investment_list',$investment_list);
        $this -> assign('contact_list',$contact_list);

        //计划
        $plan_list = $this->plan->where(['project_id' => $ids])-> order('id')->select();
        $this -> assign('plan_list',$plan_list);

        $plan_count = $this->plan->where(['project_id' => $ids,'is_standard'=>1])->count();
        $this -> assign('plan_count',$plan_count);

        // 项目阶段
        $stage_list = $this->stage -> where(['project_id' => $ids]) -> order('id') -> select();
        if(!empty($stage_list))
        {
            $progress_status_name = $stage_list[0]['progress_status_name'];
            $progress_time = $stage_list[0]['progress_status_time_text']?$stage_list[0]['progress_status_time_text']:"";
        }else{
            $progress_status_name = '';
            $progress_time = '';
        }
        $this -> assign('progress_status_name',$progress_status_name);
        $this -> assign('progress_time',$progress_time);

        // 推进详情
        $progress_list = $this->progress -> where(['project_id' => $ids]) -> order('progress_time desc') -> select();

        $this -> assign('stage_list',$stage_list);
        $this -> assign('progress_list',$progress_list);    

        //中心接洽 
        $centralcontact_list = $this->centralcontact -> where(['project_id' => $ids]) -> order('receive_time desc') -> select();
        $this -> assign('centralcontact_list',$centralcontact_list); 

        $row = $this->model->get($ids);
        $this->assign('row',$row);
        $this->assignconfig('ids',$ids);
        return $this->view->fetch();
    }

    public function analysis()
    {   
        // 2021签约
        $where_str = '';
        $str = $this->anaData($where_str);
        $this -> assign('str',$str);

        // 过亿元项目
        $guo = $this -> model -> query("select count(*) as 'projectcount',
        sum(IF(investment_total >= 1,investment_total,0)) as 'investment_total',
        SUM(IF(investment_total >= 5,1,0)) as 'over5count',
        SUM(IF(investment_total >= 5,investment_total,0)) as 'over5amount',
        SUM(IF(investment_total >= 30,1,0)) as 'over30count',
        SUM(IF(investment_total >= 30,investment_total,0)) as 'over30amount',
        SUM(IF(investment_total >= 60,1,0)) as 'over60count',
        SUM(IF(investment_total >= 60,investment_total,0)) as 'over60amount',
        SUM(IF(investment_total >= 100,1,0)) as 'over100count',
        SUM(IF(investment_total >= 100,investment_total,0)) as 'over100amount',
        sum(IF(FIND_IN_SET(1,chargedep_ids),1,0)) as 'chengyangcount',
        sum(IF(FIND_IN_SET(1,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'chengyangamount',
        sum(IF(FIND_IN_SET(2,chargedep_ids),1,0)) as 'liutingcount',
        sum(IF(FIND_IN_SET(2,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'liutingamount',
        sum(IF(FIND_IN_SET(3,chargedep_ids),1,0)) as 'xiazhuangcount',
        sum(IF(FIND_IN_SET(3,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'xiazhuangamount',
        sum(IF(FIND_IN_SET(4,chargedep_ids),1,0)) as 'xifuzhencount',
        sum(IF(FIND_IN_SET(4,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'xifuzhenamount',
        sum(IF(FIND_IN_SET(5,chargedep_ids),1,0)) as 'jihongtancount',
        sum(IF(FIND_IN_SET(5,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'jihongtanamount',
        sum(IF(FIND_IN_SET(6,chargedep_ids),1,0)) as 'shangmacount',
        sum(IF(FIND_IN_SET(6,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'shangmaamount',
        sum(IF(FIND_IN_SET(7,chargedep_ids),1,0)) as 'hetaocount',
        sum(IF(FIND_IN_SET(7,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'hetaoamount',
        sum(IF(FIND_IN_SET(8,chargedep_ids),1,0)) as 'hongdaocount',
        sum(IF(FIND_IN_SET(8,chargedep_ids),investment_total,0)) as 'hongdaoamount',
        sum(IF(FIND_IN_SET(13,chargedep_ids),1,0)) as 'guidaocount',
        sum(IF(FIND_IN_SET(13,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'guidaoamount',
        sum(IF(FIND_IN_SET(31,chargedep_ids),1,0)) as 'zonghecount',
        sum(IF(FIND_IN_SET(31,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'zongheamount',
        sum(IF(FIND_IN_SET(34,chargedep_ids),1,0)) as 'huanhaicount',
        sum(IF(FIND_IN_SET(34,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'huanhaiamount',
        sum(IF(FIND_IN_SET(26,chargedep_ids),1,0)) as 'shizhengcount',
        sum(IF(FIND_IN_SET(26,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'shizhengamount',
        sum(IF(FIND_IN_SET(27,chargedep_ids),1,0)) as 'chengshicount',
        sum(IF(FIND_IN_SET(27,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'chengshiamount',
        sum(IF(FIND_IN_SET(28,chargedep_ids),1,0)) as 'kaifacount',
        sum(IF(FIND_IN_SET(28,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'kaifaamount',
        sum(IF(FIND_IN_SET(29,chargedep_ids),1,0)) as 'dongchecount',
        sum(IF(FIND_IN_SET(29,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'dongcheamount',
        sum(IF(FIND_IN_SET(30,chargedep_ids),1,0)) as 'chuangxincount',
        sum(IF(FIND_IN_SET(30,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'chuangxinamount',
        sum(IF(FIND_IN_SET(45,chargedep_ids),1,0)) as 'nongyecount',
        sum(IF(FIND_IN_SET(45,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'nongyeamount',
        sum(IF(FIND_IN_SET(50,chargedep_ids),1,0)) as 'konggucount',
        sum(IF(FIND_IN_SET(50,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'kongguamount',
        sum(IF(FIND_IN_SET(51,chargedep_ids),1,0)) as 'xinchengcount',
        sum(IF(FIND_IN_SET(51,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'xinchengamount',
        sum(IF(FIND_IN_SET(52,chargedep_ids),1,0)) as 'hongjiancount',
        sum(IF(FIND_IN_SET(52,chargedep_ids),IF(investment_total >=1,investment_total,0),0)) as 'hongjianamount',
        sum(case five_industry_id when 1 then 1 else 0 end) as 'gaoduancount',
        sum(case five_industry_id when 2 then 1 else 0 end) as 'xinnengyuancount',
        sum(case five_industry_id when 3 then 1 else 0 end) as 'xinyidaicount',
        sum(case five_industry_id when 4 then 1 else 0 end) as 'shengwucount',
        sum(case five_industry_id when 5 then 1 else 0 end) as 'xiandaicount',
        sum(case five_industry_id when 6 then 1 else 0 end) as 'qitacount'

from ".$this->project_tablename." WHERE is_delete =0 and investment_total>=1 and progress_status_id NOT IN (9,10) and id in( select project_id from nsig_project_stage WHERE project_stage_id in(4,5) and project_stage_time>=".strtotime(date("Y")."-01-01").")" );
        $guo = $guo[0];

        // echo $this->model->getLastSql();exit();

        //单独取投资公司
        // $touzi_ids='26,27,28,29,30,45,50,51,52';
//         $touzi = $this -> model -> query("select count(*) as touzicount,SUM(investment_total) AS 'touziamount' 
// from ".$this->project_tablename." WHERE chargedep_ids IN (".$touzi_ids.") and is_delete =0 and investment_total>=1 and progress_status_id NOT IN (9,10) and id in( select project_id from nsig_project_stage WHERE project_stage_id in(4,5) and project_stage_time>=".strtotime("2021-01-01").")" );
//         $touzi = $touzi[0];

        //单独取区直部门
        // $chargedep_ids = \app\admin\model\Chargedep::where(['group_id'=>3])->column('id');
        $chargedep_ids='10,11,12,14,15,16,17,18,19,20,21,22,23,24,25,32,33,36,37,38,39,40,42,44,45,46,47,48,49,53,54,55';
        $quzhi = $this -> model -> query("select count(*) as quzhicount,SUM(investment_total) AS 'quzhiamount' 
from ".$this->project_tablename." WHERE chargedep_ids IN (".$chargedep_ids.") and is_delete =0 and investment_total>=1 and progress_status_id NOT IN (9,10) and id in( select project_id from nsig_project_stage WHERE project_stage_id in(4,5) and project_stage_time>=".strtotime(date("Y")."-01-01").")" );
        $quzhi = $quzhi[0];



        $str2 =  "2022年全区过亿元签约项目{$guo['projectcount']}个，总投资{$guo['investment_total']} 亿元。<br/>";
        $str2 .= "5亿元以上项目{$guo['over5count']}个{$guo['over5amount']}亿元，30亿元以上项目{$guo['over30count']}个{$guo['over30amount']}亿元。60亿元以上项目{$guo['over60count']}个{$guo['over60amount']}亿元，100亿元以上项目{$guo['over100count']}个{$guo['over100amount']}亿元。<br />";
        $str2 .="按街道划分：";
        if($guo['chengyangcount'] > 0)
            $str2 .= "城阳街道{$guo['chengyangcount']}个{$guo['chengyangamount']}亿元，";
        if($guo['liutingcount'] > 0)
            $str2 .= "流亭街道{$guo['liutingcount']}个{$guo['liutingamount']}亿元，";
        if($guo['xiazhuangcount'] > 0)
            $str2 .= "夏庄街道{$guo['xiazhuangcount']}个{$guo['xiazhuangamount']}亿元，";
        if($guo['xifuzhencount'] > 0)
            $str2 .= "惜福镇街道{$guo['xifuzhencount']}个{$guo['xifuzhenamount']}亿元，";
        if($guo['jihongtancount'] > 0)
            $str2 .= "棘洪滩街道{$guo['jihongtancount']}个{$guo['jihongtanamount']}亿元，";
        if($guo['shangmacount'] > 0)
            $str2 .= "上马街道{$guo['shangmacount']}个{$guo['shangmaamount']}亿元，";
        if($guo['hongdaocount'] > 0)
            $str2 .= "红岛街道{$guo['hongdaocount']}个{$guo['hongdaoamount']}亿元，";
        if($guo['hetaocount'] > 0)
            $str2 .= "河套街道{$guo['hetaocount']}个{$guo['hetaoamount']}亿元，";
        if($guo['guidaocount'] > 0)
            $str2 .= "轨道交通产业示范区{$guo['guidaocount']}个{$guo['guidaoamount']}亿元，";
        if($guo['zonghecount'] > 0)
            $str2 .= "胶州湾综合保税区{$guo['zonghecount']}个{$guo['zongheamount']}亿元，";
        if($guo['huanhaicount'] > 0)
            $str2 .= "环海经济开发区{$guo['huanhaicount']}个{$guo['huanhaiamount']}亿元，";
        
        if($guo['shizhengcount'] > 0)
            $str2 .= "城阳市政投资集团{$guo['shizhengcount']}个{$guo['shizhengamount']}亿元，";
        if($guo['chengshicount'] > 0)
            $str2 .= "城阳城市发展集团有限公司{$guo['chengshicount']}个{$guo['chengshiamount']}亿元，";
        if($guo['kaifacount'] > 0)
            $str2 .= "城阳开发投资集团有限公司{$guo['kaifacount']}个{$guo['kaifaamount']}亿元，";
        if($guo['dongchecount'] > 0)
            $str2 .= "动车小镇投资公司{$guo['dongchecount']}个{$guo['dongcheamount']}亿元，";
        if($guo['chuangxincount'] > 0)
            $str2 .= "城阳阳光创新投资有限公司{$guo['chuangxincount']}个{$guo['chuangxinamount']}亿元，";
        if($guo['nongyecount'] > 0)
            $str2 .= "阳光农业发展投资有限公司{$guo['nongyecount']}个{$guo['nongyeamount']}亿元，";
        if($guo['konggucount'] > 0)
            $str2 .= "城阳区阳光城阳控股集团有限公司{$guo['konggucount']}个{$guo['kongguamount']}亿元，";
        if($guo['xinchengcount'] > 0)
            $str2 .= "青岛环海新城投资有限公司{$guo['xinchengcount']}个{$guo['xinchengamount']}亿元，";
        if($guo['hongjiancount'] > 0)
            $str2 .= "青岛红建投资有限公司{$guo['hongjiancount']}个{$guo['hongjianamount']}亿元，";


        if($quzhi['quzhicount'] > 0)
            $str2 .= "区直部门{$quzhi['quzhicount']}个{$quzhi['quzhiamount']}亿元，";


        $str2 .="<br>";
        $str2 .="按五大产业划分：高端装备{$guo['gaoduancount']}个，新一代信息技术{$guo['xinyidaicount']}个，新材料新能源{$guo['xinnengyuancount']}个，生物医药{$guo['shengwucount']}个，现代服务业{$guo['xiandaicount']}个,其他{$guo['qitacount']}个。<br>";

        $this -> assign('str2',$str2);

        $nan = $this -> model -> query("select count(*) as 'projectcount',
            sum(IF(investment_total > 0,investment_total,0)) as 'investment_total',
            sum(IF(FIND_IN_SET(1,chargedep_ids),1,0)) as 'chengyangcount',
            sum(IF(FIND_IN_SET(1,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'chengyangamount',
            sum(IF(FIND_IN_SET(2,chargedep_ids),1,0)) as 'liutingcount',
            sum(IF(FIND_IN_SET(2,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'liutingamount',
            sum(IF(FIND_IN_SET(3,chargedep_ids),1,0)) as 'xiazhuangcount',
            sum(IF(FIND_IN_SET(3,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'xiazhuangamount',
            sum(IF(FIND_IN_SET(4,chargedep_ids),1,0)) as 'xifuzhencount',
            sum(IF(FIND_IN_SET(4,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'xifuzhenamount',
            sum(IF(FIND_IN_SET(5,chargedep_ids),1,0)) as 'jihongtancount',
            sum(IF(FIND_IN_SET(5,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'jihongtanamount',
            sum(IF(FIND_IN_SET(6,chargedep_ids),1,0)) as 'shangmacount',
            sum(IF(FIND_IN_SET(6,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'shangmaamount',
            sum(IF(FIND_IN_SET(7,chargedep_ids),1,0)) as 'hetaocount',
            sum(IF(FIND_IN_SET(7,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'hetaoamount',
            sum(IF(FIND_IN_SET(8,chargedep_ids),1,0)) as 'hongdaocount',
            sum(IF(FIND_IN_SET(8,chargedep_ids),investment_total,0)) as 'hongdaoamount',
            sum(IF(FIND_IN_SET(13,chargedep_ids),1,0)) as 'guidaocount',
            sum(IF(FIND_IN_SET(13,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'guidaoamount',
            sum(IF(FIND_IN_SET(14,chargedep_ids),1,0)) as 'jinrongcount',
            sum(IF(FIND_IN_SET(14,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'jinrongamount',
            sum(IF(FIND_IN_SET(15,chargedep_ids),1,0)) as 'dashujucount',
            sum(IF(FIND_IN_SET(15,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'dashujuamount',
            sum(IF(FIND_IN_SET(29,chargedep_ids),1,0)) as 'dongchecount',
            sum(IF(FIND_IN_SET(29,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'dongcheamount',
            sum(IF(FIND_IN_SET(30,chargedep_ids),1,0)) as 'ygctcount',
            sum(IF(FIND_IN_SET(30,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'ygctamount',
            sum(IF(FIND_IN_SET(31,chargedep_ids),1,0)) as 'zonghecount',
            sum(IF(FIND_IN_SET(31,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'zongheamount',
            sum(IF(FIND_IN_SET(34,chargedep_ids),1,0)) as 'huanhaicount',
            sum(IF(FIND_IN_SET(34,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'huanhaiamount',
            sum(IF(FIND_IN_SET(26,chargedep_ids),1,0)) as 'shizhengcount',
            sum(IF(FIND_IN_SET(26,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'shizhengamount',
            sum(IF(FIND_IN_SET(27,chargedep_ids),1,0)) as 'chengshicount',
            sum(IF(FIND_IN_SET(27,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'chengshiamount',
            sum(IF(FIND_IN_SET(28,chargedep_ids),1,0)) as 'kaifacount',
            sum(IF(FIND_IN_SET(28,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'kaifaamount',
            sum(IF(FIND_IN_SET(29,chargedep_ids),1,0)) as 'dongchecount',
            sum(IF(FIND_IN_SET(29,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'dongcheamount',
            sum(IF(FIND_IN_SET(30,chargedep_ids),1,0)) as 'chuangxincount',
            sum(IF(FIND_IN_SET(30,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'chuangxinamount',
            sum(IF(FIND_IN_SET(45,chargedep_ids),1,0)) as 'nongyecount',
            sum(IF(FIND_IN_SET(45,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'nongyeamount',
            sum(IF(FIND_IN_SET(50,chargedep_ids),1,0)) as 'konggucount',
            sum(IF(FIND_IN_SET(50,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'kongguamount',
            sum(IF(FIND_IN_SET(51,chargedep_ids),1,0)) as 'xinchengcount',
            sum(IF(FIND_IN_SET(51,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'xinchengamount',
            sum(IF(FIND_IN_SET(52,chargedep_ids),1,0)) as 'hongjiancount',
            sum(IF(FIND_IN_SET(52,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'hongjianamount',
            sum(case five_industry_id when 1 then 1 else 0 end) as 'gaoduancount',
            sum(case five_industry_id when 2 then 1 else 0 end) as 'xinnengyuancount',
            sum(case five_industry_id when 3 then 1 else 0 end) as 'xinyidaicount',
            sum(case five_industry_id when 4 then 1 else 0 end) as 'shengwucount',
            sum(case five_industry_id when 5 then 1 else 0 end) as 'xiandaicount',
            sum(case five_industry_id when 6 then 1 else 0 end) as 'qitacount'
        from ".$this->project_tablename." p where p.is_delete =0 and p.progress_status_id =1");
        $nan = $nan[0];

        // 投资公司
        // $touzinan = $this -> model -> query("select count(*) as touzicount,SUM(investment_total) AS 'touziamount'
        // from ".$this->project_tablename." p where p.chargedep_ids IN (".$touzi_ids.") and p.is_delete =0 and p.progress_status_id =1");
        // $touzinan = $touzinan[0];

        //区直部门
        $quzhinan = $this -> model -> query("select count(*) as quzhicount,SUM(investment_total) AS 'quzhiamount'
        from ".$this->project_tablename." p where p.chargedep_ids IN (".$chargedep_ids.") and p.is_delete =0 and p.progress_status_id =1");
        $quzhinan = $quzhinan[0];


        $str1 = "2022年截至目前，全区在谈项目{$nan['projectcount']}个，计划总投资{$nan['investment_total']}亿元。<br />";
        $str1 .="按街道划分：";
        if($nan['chengyangcount'] > 0)
            $str1 .= "城阳街道{$nan['chengyangcount']}个{$nan['chengyangamount']}亿元，";
        if($nan['liutingcount'] > 0)
            $str1 .= "流亭街道{$nan['liutingcount']}个{$nan['liutingamount']}亿元，";
        if($nan['xiazhuangcount'] > 0)
            $str1 .= "夏庄街道{$nan['xiazhuangcount']}个{$nan['xiazhuangamount']}亿元，";
        if($nan['xifuzhencount'] > 0)
            $str1 .= "惜福镇街道{$nan['xifuzhencount']}个{$nan['xifuzhenamount']}亿元，";
        if($nan['jihongtancount'] > 0)
            $str1 .= "棘洪滩街道{$nan['jihongtancount']}个{$nan['jihongtanamount']}亿元，";
        if($nan['shangmacount'] > 0)
            $str1 .= "上马街道{$nan['shangmacount']}个{$nan['shangmaamount']}亿元，";
        if($nan['hongdaocount'] > 0)
            $str1 .= "红岛街道{$nan['hongdaocount']}个{$nan['hongdaoamount']}亿元，";
        if($nan['hetaocount'] > 0)
            $str1 .= "河套街道{$nan['hetaocount']}个{$nan['hetaoamount']}亿元，";
        if($nan['guidaocount'] > 0)
            $str1 .= "轨道交通产业示范区{$nan['guidaocount']}个{$nan['guidaoamount']}亿元，";
        if($nan['zonghecount'] > 0)
            $str1 .= "胶州湾综合保税区{$nan['zonghecount']}个{$nan['zongheamount']}亿元，";
        if($nan['huanhaicount'] > 0)
            $str1 .= "环海经济开发区{$nan['huanhaicount']}个{$nan['huanhaiamount']}亿元，";
        // if($touzinan['touzicount'] > 0)
        //     $str1 .= "投资公司{$touzinan['touzicount']}个{$touzinan['touziamount']}亿元，";
        if($nan['shizhengcount'] > 0)
            $str1 .= "城阳市政投资集团{$nan['shizhengcount']}个{$nan['shizhengamount']}亿元，";
        if($nan['chengshicount'] > 0)
            $str1 .= "城阳城市发展集团有限公司{$nan['chengshicount']}个{$nan['chengshiamount']}亿元，";
        if($nan['kaifacount'] > 0)
            $str1 .= "城阳开发投资集团有限公司{$nan['kaifacount']}个{$nan['kaifaamount']}亿元，";
        if($nan['dongchecount'] > 0)
            $str1 .= "动车小镇投资公司{$nan['dongchecount']}个{$nan['dongcheamount']}亿元，";
        if($nan['chuangxincount'] > 0)
            $str1 .= "城阳阳光创新投资有限公司{$nan['chuangxincount']}个{$nan['chuangxinamount']}亿元，";
        if($nan['nongyecount'] > 0)
            $str1 .= "阳光农业发展投资有限公司{$nan['nongyecount']}个{$nan['nongyeamount']}亿元，";
        if($nan['konggucount'] > 0)
            $str1 .= "城阳区阳光城阳控股集团有限公司{$nan['konggucount']}个{$nan['kongguamount']}亿元，";
        if($nan['xinchengcount'] > 0)
            $str1 .= "青岛环海新城投资有限公司{$nan['xinchengcount']}个{$nan['xinchengamount']}亿元，";
        if($nan['hongjiancount'] > 0)
            $str1 .= "青岛红建投资有限公司{$nan['hongjiancount']}个{$nan['hongjianamount']}亿元，";

        if($quzhinan['quzhicount'] > 0)
            $str1 .= "区直部门{$quzhinan['quzhicount']}个{$quzhinan['quzhiamount']}亿元，";

       
        $str1 .="<br>";
        $str1 .="按五大产业划分：高端装备{$nan['gaoduancount']}个，新一代信息技术{$nan['xinyidaicount']}个，新材料新能源{$nan['xinnengyuancount']}个，生物医药{$nan['shengwucount']}个，现代服务业{$nan['xiandaicount']}个,其他{$nan['qitacount']}个。<br>";
        $this -> assign('str1',$str1);


        // 街道更新
        $street = $this -> model -> query("select count(*) as 'projectcount',
            sum(case chargedep_ids when 1 then 1 else 0 end) as 'chengyangcount',
            sum(IF(FIND_IN_SET(1,chargedep_ids),IF(`status` = 1,status,0),0)) as 'chengyangupdate',
            sum(case chargedep_ids when 2 then 1 else 0 end) as 'liutingcount',
            sum(IF(FIND_IN_SET(2,chargedep_ids),IF(`status` = 1,status,0),0)) as 'liutingupdate',
            sum(case chargedep_ids when 3 then 1 else 0 end) as 'xiazhuangcount',
            sum(IF(FIND_IN_SET(3,chargedep_ids),IF(`status` = 1,status,0),0)) as 'xiazhuangupdate',
            sum(case chargedep_ids when 4 then 1 else 0 end) as 'xifuzhencount',
            sum(IF(FIND_IN_SET(4,chargedep_ids),IF(`status` = 1,status,0),0)) as 'xifuzhenupdate',
            sum(case chargedep_ids when 5 then 1 else 0 end) as 'jihongtancount',
            sum(IF(FIND_IN_SET(5,chargedep_ids),IF(`status` = 1,status,0),0)) as 'jihongtanupdate',
            sum(case chargedep_ids when 6 then 1 else 0 end) as 'shangmacount',
            sum(IF(FIND_IN_SET(6,chargedep_ids),IF(`status` = 1,status,0),0)) as 'shangmaupdate',
            sum(case chargedep_ids when 7 then 1 else 0 end) as 'hetaocount',
            sum(IF(FIND_IN_SET(7,chargedep_ids),IF(`status` = 1,status,0),0)) as 'hetaoupdate',
            sum(case chargedep_ids when 8 then 1 else 0 end) as 'hongdaocount',
            sum(IF(FIND_IN_SET(8,chargedep_ids),IF(`status` = 1,status,0),0)) as 'hongdaoupdate',
            sum(case chargedep_ids when 9 then 1 else 0 end) as 'zhaoshangcount',
            sum(IF(FIND_IN_SET(9,chargedep_ids),IF(`status` = 1,status,0),0)) as 'zhaoshangupdate',
            sum(case chargedep_ids when 13 then 1 else 0 end) as 'guidaocount',
            sum(IF(FIND_IN_SET(13,chargedep_ids),IF(`status` = 1,status,0),0)) as 'guidaoupdate',
            sum(case chargedep_ids when 31 then 1 else 0 end) as 'zongbaocount',
            sum(IF(FIND_IN_SET(31,chargedep_ids),IF(`status` = 1,status,0),0)) as 'zongbaoupdate',
            sum(case chargedep_ids when 34 then 1 else 0 end) as 'huanhaicount',
            sum(IF(FIND_IN_SET(34,chargedep_ids),IF(`status` = 1,status,0),0)) as 'huanhaiupdate',

            sum(case chargedep_ids when 26 then 1 else 0 end) as 'sztzcount',
            sum(IF(FIND_IN_SET(26,chargedep_ids),IF(`status` = 1,status,0),0)) as 'sztzupdate',
            sum(case chargedep_ids when 27 then 1 else 0 end) as 'fzjtcount',
            sum(IF(FIND_IN_SET(27,chargedep_ids),IF(`status` = 1,status,0),0)) as 'fzjtupdate',
            sum(case chargedep_ids when 28 then 1 else 0 end) as 'kftzcount',
            sum(IF(FIND_IN_SET(28,chargedep_ids),IF(`status` = 1,status,0),0)) as 'kftzupdate',
            sum(case chargedep_ids when 29 then 1 else 0 end) as 'dcxztzcount',
            sum(IF(FIND_IN_SET(29,chargedep_ids),IF(`status` = 1,status,0),0)) as 'dcxztzupdate',
            sum(case chargedep_ids when 30 then 1 else 0 end) as 'cxtzcount',
            sum(IF(FIND_IN_SET(30,chargedep_ids),IF(`status` = 1,status,0),0)) as 'cxtzupdate',
            sum(case chargedep_ids when 45 then 1 else 0 end) as 'nyfztzcount',
            sum(IF(FIND_IN_SET(45,chargedep_ids),IF(`status` = 1,status,0),0)) as 'nyfztzupdate',
            sum(case chargedep_ids when 50 then 1 else 0 end) as 'ygkgcount',
            sum(IF(FIND_IN_SET(50,chargedep_ids),IF(`status` = 1,status,0),0)) as 'ygkgupdate',
            sum(case chargedep_ids when 51 then 1 else 0 end) as 'hhxctzcount',
            sum(IF(FIND_IN_SET(51,chargedep_ids),IF(`status` = 1,status,0),0)) as 'hhxctzupdate',
            sum(case chargedep_ids when 52 then 1 else 0 end) as 'hjtzcount',
            sum(IF(FIND_IN_SET(28,chargedep_ids),IF(`status` = 1,status,0),0)) as 'hjtzupdate'

        from ".$this->project_tablename." where is_delete=0 and progress_status_id<9");
        $street = $street[0];

        $str3= '<span style="background-color:#faebcc;font-weight:900;">功能区汇总：</span><br/>';
        if($street['guidaoupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>轨道交通产业示范区</span>:已更新{$street['guidaoupdate']}个,总数{$street['guidaocount']}个，更新率".number_format($street['guidaoupdate']/$street['guidaocount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>轨道交通产业示范区</span>:已更新0个,总数{$street['guidaocount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['huanhaiupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛环海经济开发区管委会</span>:已更新{$street['huanhaiupdate']}个,总数{$street['huanhaicount']}个，更新率".number_format($street['huanhaiupdate']/$street['huanhaicount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛环海经济开发区管委会</span>:已更新0个,总数{$street['huanhaicount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['zongbaoupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>胶州湾综合保税区</span>:已更新{$street['zongbaoupdate']}个,总数{$street['zongbaocount']}个，更新率".number_format($street['zongbaoupdate']/$street['zongbaocount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>胶州湾综合保税区</span>:已更新0个,总数{$street['zongbaocount']}个，更新率0;&nbsp;&nbsp;&nbsp;";


        $str3.= '<br/><span style="background-color:#faebcc;font-weight:900;">街道汇总</span>：<br/>';
        if($street['chengyangupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳街道</span>:已更新{$street['chengyangupdate']}个,总数{$street['chengyangcount']}个，更新率".number_format($street['chengyangupdate']/$street['chengyangcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳街道</span>:已更新0个,总数{$street['chengyangcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['liutingupdate'] > 0)
            $str3 .="<span style='color:#3498db;font-weight:900;'>流亭街道</span>:已更新{$street['liutingupdate']}个,总数{$street['liutingcount']}个，更新率".number_format($street['liutingupdate']/$street['liutingcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>流亭街道</span>:已更新0个,总数{$street['liutingcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['xiazhuangupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>夏庄街道</span>:已更新{$street['xiazhuangupdate']}个,总数{$street['xiazhuangcount']}个，更新率".number_format($street['xiazhuangupdate']/$street['xiazhuangcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>夏庄街道</span>:已更新0个,总数{$street['xiazhuangcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['xifuzhenupdate'] > 0)
            $str3 .="<span style='color:#3498db;font-weight:900;'>惜福镇街道</span>:已更新{$street['xifuzhenupdate']}个,总数{$street['xifuzhencount']}个，更新率".number_format($street['xifuzhenupdate']/$street['xifuzhencount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>惜福镇街道</span>:已更新0个,总数{$street['xifuzhencount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['jihongtanupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>棘洪滩街道</span>:已更新{$street['jihongtanupdate']}个,总数{$street['jihongtancount']}个，更新率".number_format($street['jihongtanupdate']/$street['jihongtancount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>棘洪滩街道</span>:已更新0个,总数{$street['jihongtancount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['shangmaupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>上马街道</span>:已更新{$street['shangmaupdate']}个,总数{$street['shangmacount']}个，更新率".number_format($street['shangmaupdate']/$street['shangmacount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>上马街道</span>:已更新0个,总数{$street['shangmacount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['hetaoupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>河套街道</span>:已更新{$street['hetaoupdate']}个,总数{$street['hetaocount']}个，更新率".number_format($street['hetaoupdate']/$street['hetaocount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>河套街道</span>:已更新0个,总数{$street['hetaocount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['hongdaoupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>红岛街道</span>:已更新{$street['hongdaoupdate']}个,总数{$street['hongdaocount']}个，更新率".number_format($street['hongdaoupdate']/$street['hongdaocount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>红岛街道</span>:已更新0个,总数{$street['hongdaocount']}个，更新率0;&nbsp;&nbsp;&nbsp;";


        $str3.= '<br/><span style="background-color:#faebcc;font-weight:900;">区直企业汇总：</span><br/>';

        if($street['kftzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳开发投资集团有限公司</span>:已更新{$street['kftzupdate']}个,总数{$street['kftzcount']}个，更新率".number_format($street['kftzupdate']/$street['kftzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳开发投资集团有限公司</span>:已更新0个,总数{$street['kftzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['sztzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳市政投资集团</span>:已更新{$street['sztzupdate']}个,总数{$street['sztzcount']}个，更新率".number_format($street['sztzupdate']/$street['sztzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳市政投资集团</span>:已更新0个,总数{$street['sztzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['fzjtupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳城市发展集团有限公司</span>:已更新{$street['fzjtupdate']}个,总数{$street['fzjtcount']}个，更新率".number_format($street['fzjtupdate']/$street['fzjtcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳城市发展集团有限公司</span>:已更新0个,总数{$street['fzjtcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['ygkgupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛市城阳区阳光城阳控股集团有限公司</span>:已更新{$street['ygkgupdate']}个,总数{$street['ygkgcount']}个，更新率".number_format($street['ygkgupdate']/$street['ygkgcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛市城阳区阳光城阳控股集团有限公司</span>:已更新0个,总数{$street['ygkgcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['cxtzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳阳光创新投资有限公司</span>:已更新{$street['cxtzupdate']}个,总数{$street['cxtzcount']}个，更新率".number_format($street['cxtzupdate']/$street['cxtzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>城阳阳光创新投资有限公司</span>:已更新0个,总数{$street['cxtzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['dcxztzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>动车小镇投资公司</span>:已更新{$street['dcxztzupdate']}个,总数{$street['dcxztzcount']}个，更新率".number_format($street['dcxztzupdate']/$street['dcxztzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>动车小镇投资公司</span>:已更新0个,总数{$street['dcxztzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['hhxctzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛环海新城投资有限公司</span>:已更新{$street['hhxctzupdate']}个,总数{$street['hhxctzcount']}个，更新率".number_format($street['hhxctzupdate']/$street['hhxctzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛环海新城投资有限公司</span>:已更新0个,总数{$street['hhxctzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['hjtzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛红建投资有限公司</span>:已更新{$street['hjtzupdate']}个,总数{$street['hjtzcount']}个，更新率".number_format($street['hjtzupdate']/$street['hjtzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>青岛红建投资有限公司</span>:已更新0个,总数{$street['hjtzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        if($street['nyfztzupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>阳光农业发展投资有限公司</span>:已更新{$street['nyfztzupdate']}个,总数{$street['nyfztzcount']}个，更新率".number_format($street['nyfztzupdate']/$street['nyfztzcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>阳光农业发展投资有限公司</span>:已更新0个,总数{$street['nyfztzcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";

        $str3.= '<br/><span style="background-color:#faebcc;font-weight:900;">区直部门汇总：</span><br/>';
        if($street['zhaoshangupdate'] > 0)
            $str3 .= "<span style='color:#3498db;font-weight:900;'>招商促进中心</span>:已更新{$street['zhaoshangupdate']}个,总数{$street['zhaoshangcount']}个，更新率".number_format($street['zhaoshangupdate']/$street['zhaoshangcount']*100)."%&nbsp;&nbsp;&nbsp;";
        else
            $str3 .= "<span style='color:#3498db;font-weight:900;'>招商促进中心</span>:已更新0个,总数{$street['zhaoshangcount']}个，更新率0;&nbsp;&nbsp;&nbsp;";
            

        $zhaoshang_arr = [
            ['label'=>'招商一科','id'=>1  ,'count'=>0,'updatecount'=>0],
            ['label'=>'招商二科','id'=>2  ,'count'=>0,'updatecount'=>0],
            ['label'=>'招商三科','id'=>3  ,'count'=>0,'updatecount'=>0],
            ['label'=>'招商四科','id'=>4  ,'count'=>0,'updatecount'=>0],
            ['label'=>'招商五科','id'=>5  ,'count'=>0,'updatecount'=>0],
            ['label'=>'招商六科','id'=>6  ,'count'=>0,'updatecount'=>0],
            ['label'=>'综合科','id'=>7  ,'count'=>0,'updatecount'=>0],
            ['label'=>'产业发展科','id'=>8  ,'count'=>0,'updatecount'=>0],
            ['label'=>'平台建设科','id'=>9  ,'count'=>0,'updatecount'=>0],
            ['label'=>'重点项目科','id'=>10  ,'count'=>0,'updatecount'=>0],
        ];
        foreach($zhaoshang_arr as $key =>$v)
        {
            $zhaoshang_list = $this -> model -> query("select c.project_id,p.status FROM nsig_project_centralcontact c,nsig_project_new p  WHERE FIND_IN_SET(".$v['id'].",c.centraloffice_id) and c.project_id = p.id and  p.is_delete=0 and p.progress_status_id<9 GROUP BY c.project_id ");
            foreach($zhaoshang_list as $k =>$vv)
            {
                if($vv['status']==1)
                    $zhaoshang_arr[$key]['updatecount']++;  
            }
            $zhaoshang_arr[$key]['count'] = count($zhaoshang_list); 
        }   

        $str3.= '<br/><span style="background-color:#faebcc;font-weight:900;">区招商促进中心汇总:</span><br/>';
        foreach($zhaoshang_arr as $ky =>$v1)
        {
            if($v1['updatecount'] > 0)
                $str3 .= "<span style='color:#3498db;font-weight:900;'>".$v1['label']."</span>:已更新".$v1['updatecount']."个,总数".$v1['count']."个，更新率".number_format($v1['updatecount']/$v1['count']*100)."%&nbsp;&nbsp;&nbsp;";
            else
                $str3 .= "<span style='color:#3498db;font-weight:900;'>".$v1['label']."</span>:已更新0个,总数".$v1['count']."个，更新率0;&nbsp;&nbsp;&nbsp;";
        }
        $this -> assign('str3',$str3);



        // 项目准入情况
        $zhunru = $this -> model -> query("select count(*) as 'projectcount',
            sum(IF(FIND_IN_SET(34,p.chargedep_ids),1,0)) as 'huanhaicount',
            sum(IF(FIND_IN_SET(31,p.chargedep_ids),1,0)) as 'zonghecount',
            sum(IF(FIND_IN_SET(13,p.chargedep_ids),1,0)) as 'jiaozhoucount',
            sum(IF(FIND_IN_SET(1,p.chargedep_ids),1,0)) as 'chengyangcount',
            sum(IF(FIND_IN_SET(2,p.chargedep_ids),1,0)) as 'liutingcount',
            sum(IF(FIND_IN_SET(3,p.chargedep_ids),1,0)) as 'xiazhuangcount',
            sum(IF(FIND_IN_SET(4,p.chargedep_ids),1,0)) as 'xifuzhencount',
            sum(IF(FIND_IN_SET(5,p.chargedep_ids),1,0)) as 'jihongtancount',
            sum(IF(FIND_IN_SET(6,p.chargedep_ids),1,0)) as 'shangmacount',
            sum(IF(FIND_IN_SET(7,p.chargedep_ids),1,0)) as 'hetaocount',
            sum(IF(FIND_IN_SET(8,p.chargedep_ids),1,0)) as 'hongdaocount',
            
            sum(IF(FIND_IN_SET(26,chargedep_ids),1,0)) as 'shizhengcount',
            sum(IF(FIND_IN_SET(27,chargedep_ids),1,0)) as 'chengshicount',
            sum(IF(FIND_IN_SET(28,chargedep_ids),1,0)) as 'kaifacount',
            sum(IF(FIND_IN_SET(29,chargedep_ids),1,0)) as 'dongchecount',
            sum(IF(FIND_IN_SET(30,chargedep_ids),1,0)) as 'chuangxincount',
            sum(IF(FIND_IN_SET(45,chargedep_ids),1,0)) as 'nongyecount',
            sum(IF(FIND_IN_SET(50,chargedep_ids),1,0)) as 'konggucount',
            sum(IF(FIND_IN_SET(51,chargedep_ids),1,0)) as 'xinchengcount',
            sum(IF(FIND_IN_SET(52,chargedep_ids),1,0)) as 'hongjiancount',

            sum(case p.industry_category_id when 6 then 1 else 0 end) as 'nongyecount',
            sum(case p.industry_category_id when 7 then 1 else 0 end) as 'zhizaoyecount',
            sum(case p.industry_category_id when 8 then 1 else 0 end) as 'jianzhuyecount',
            sum(case p.industry_category_id when 9 then 1 else 0 end) as 'fuwuyecount',
            sum(case p.industry_category_id when 10 then 1 else 0 end) as 'fangdichancount',
            sum(case p.industry_category_id when 11 then 1 else 0 end) as 'ronghecount',
            sum(case p.industry_category_id when 12 then 1 else 0 end) as 'keyancount'
            FROM nsig_project_stage s ,nsig_project_new p  WHERE s.project_id = p.id and  p.is_delete=0 and s.project_stage_id=3");
        $zhunru = $zhunru[0];

        // // 投资公司
        // $touzi_zhunru = $this -> model -> query("select count(*) as 'touzicount'
        //     FROM nsig_project_stage s ,nsig_project_new p  WHERE s.project_id = p.id and p.chargedep_ids IN (".$touzi_ids.") and p.is_delete=0 and s.project_stage_id=3");
        // $touzi_zhunru = $touzi_zhunru[0];


        // 区直部门
        $quzhi_zhunru = $this -> model -> query("select count(*) as 'quzhicount'
            FROM nsig_project_stage s ,nsig_project_new p  WHERE s.project_id = p.id and p.chargedep_ids IN (".$chargedep_ids.") and p.is_delete=0 and s.project_stage_id=3");
        $quzhi_zhunru = $quzhi_zhunru[0];

        // 已拿地
        $nadi = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_id IN ( SELECT project_id FROM nsig_project_stage WHERE project_stage_id=3) and project_stage_id=7");
        $nadi = $nadi[0];

        // 年份
        $year_arr = [
            ['label'=>2017,'id'=>1,'count'=>0],
            ['label'=>2018,'id'=>2,'count'=>0],
            ['label'=>2019,'id'=>3,'count'=>0],
            ['label'=>2020,'id'=>4,'count'=>0],
            ['label'=>2021,'id'=>5,'count'=>0],
            ['label'=>2022,'id'=>6,'count'=>0],
        ];
        foreach($year_arr as $key =>$vv)
        {
            if($vv['id']==1){ //2017
                $year_list = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_stage_id=3 and project_stage_time>'1483200000' and project_stage_time<'1514736000'");
            }else if($vv['id']==2){ //2018
                $year_list = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_stage_id=3 and project_stage_time>'1514736000' and project_stage_time<'1546272000'");
            }else if($vv['id']==3){ //2019
                $year_list = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_stage_id=3 and project_stage_time>'1546272000' and project_stage_time<'1577808000'");
            }else if($vv['id']==4){ //2020
                $year_list = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_stage_id=3 and project_stage_time>'1577808000' and project_stage_time<'1609430400'");
            }else if($vv['id']==5){ //2021
                $year_list = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_stage_id=3 and project_stage_time>'1609430400' and project_stage_time<'1640966400'");
            }else if($vv['id']==6){ //2021
                $year_list = $this -> model -> query("SELECT COUNT(*) as zong FROM nsig_project_stage WHERE project_stage_id=3 and project_stage_time>'1640966400' and project_stage_time<'1672502400'");
            }
            $year_list = $year_list[0];
            $year_arr[$key]['count'] = $year_list['zong'];   
        }

        $str4 = "2017年以来全区共准入项目{$zhunru['projectcount']}个，其中已拿地项目{$nadi['zong']}个。 <br/> {$zhunru['projectcount']}个准入项目中，";
        foreach($year_arr as $ky =>$vv3)
        {
            $str4 .= $vv3['label']."年准入".$vv3['count']."个，";
        }
        $str4 .= "<br/>城阳街道准入{$zhunru['chengyangcount']}个，流亭街道准入{$zhunru['liutingcount']}个，夏庄街道准入{$zhunru['xiazhuangcount']}个，惜福镇街道准入{$zhunru['xifuzhencount']}个，棘洪滩街道准入{$zhunru['jihongtancount']}个，上马街道准入{$zhunru['shangmacount']}个，红岛街道准入{$zhunru['hongdaocount']}个，河套街道准入{$zhunru['hetaocount']}个，轨道交通产业示范区准入{$zhunru['jiaozhoucount']}个，胶州湾综合保税区准入{$zhunru['zonghecount']}个，环海经济开发区准入{$zhunru['huanhaicount']}个，城阳市政投资集团{$zhunru['shizhengcount']}个，城阳城市发展集团有限公司{$zhunru['chengshicount']}个，城阳开发投资集团有限公司{$zhunru['kaifacount']}个，动车小镇投资公司{$zhunru['dongchecount']}个，城阳阳光创新投资有限公司{$zhunru['chuangxincount']}个，阳光农业发展投资有限公司{$zhunru['nongyecount']}个，城阳区阳光城阳控股集团有限公司{$zhunru['konggucount']}个，青岛环海新城投资有限公司{$zhunru['xinchengcount']}个，青岛红建投资有限公司{$zhunru['hongjiancount']}个，区直部门准入{$quzhi_zhunru['quzhicount']}个<br/>";
        $str4 .= "{$zhunru['projectcount']}个准入项目中，制造业项目{$zhunru['zhizaoyecount']}个，服务业{$zhunru['fuwuyecount']}个，产城融合{$zhunru['ronghecount']}个。";

        $this -> assign('str4',$str4);
        return $this->view->fetch();
    }

    /**
     * [detail description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function detail($ids = null) {
        $row = $this->model->get($ids);
        if(!$row) {
            $this->error(__('No Results were found'));
        }
        // echo $this->model->getLastSql();
        $plan_list = $this->plan->where(['project_id' => $row -> id])-> order('id')->select();
        $stage_list = $this->stage -> where(['project_id' => $row -> id,'status'=>1]) -> order('id') -> select();
        $progress_list = $this->progress -> where(['project_id' => $row -> id,'status'=>1]) -> order('id') -> select();


        //投资方 
        $investment_list = $this->investment->where(['project_id' => $row -> id])->order('id')->select();

        // 协办单位
        $contact_list = $this->contacts->where(['project_id' => $row -> id])->order('id')->select();

        // 接洽记录
        $central_list = $this->centralcontact->where(['project_id' => $row -> id])-> order('id')->select();

        $this -> assign('plan_list',$plan_list);
        $this -> assign('stage_list',$stage_list);
        $this -> assign('progress_list',$progress_list);
        $this -> assign('central_list',$central_list);

        $this -> assign('investment_list',$investment_list);
        $this -> assign('contact_list',$contact_list);

        $this->view->assign("row", $row);
        $this->assignconfig('ids',$ids);
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
        return $this->view->fetch();
    }

    /**
     * [stage description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function stage($ids = null)
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->where['project_id'] = $ids;
            // $this->where['status'] = 1;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->stage->with($this->relationtTable)
                ->where($where)
                ->where($this->where)
                ->order('id asc')
                ->count();
            $list = $this->stage->with($this->relationtTable)
                ->where($where)
                ->where($this->where)
                ->order('id asc')
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();
    }


    /**
     * [addstage description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function addstage($ids = null)
    {
        $row = $this -> model -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            if(isset($data['project_stage_id'])){
                $data['project_stage_name'] = Config::get('app.project_status')[$data['project_stage_id']];
            }
            if(isset($data['progress_status_id'])){
                $data['progress_status_name'] = Config::get('app.project_status')[$data['progress_status_id']];
            }
            $data['report_id'] = $this-> auth ->id;
            $data['report_name'] = $this-> auth ->nickname;
            $data['year'] = date("Y",time());
            $data['status'] = -1;
            $ret = $this->stage-> save($data);
            if($ret){
                // 同时把项目阶段更新到主表，带审核状态。
                if(isset($data['progress_status_id']))
                {
                    $row->progress_status_id = $data['progress_status_id'];
                    $row->progress_status_name = $data['progress_status_name'];                    
                }
                $row->progress_status_time = time();
                $row->status = -1 ;
                $row->update_status = 1;
                $row->is_new = 1;
                $row->save();
                $this -> success('添加成功');
            }
        }    
        $this ->assign('row',$row);
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();      
    }

    /**
     * [editstage description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function editstage($ids = null)
    {
        $row = $this -> stage -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            if(isset($data['project_stage_id'])){
                $data['project_stage_name'] = Config::get('app.project_status')[$data['project_stage_id']];
            }
            if(isset($data['progress_status_id'])){
                $data['progress_status_name'] = Config::get('app.project_status')[$data['progress_status_id']];
            }
            $data['report_id'] = $this-> auth ->id;
            $data['report_name'] = $this-> auth ->nickname;
            $data['year'] = date("Y",time());
            $data['status'] = -1;

            $ret = $row->allowField(true) -> save($data);
            if($ret)
                $this -> success('更新成功');
        } 
        $this ->assign('row',$row);
        return $this->view->fetch();
    }


    /**
     * [viewstage description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function viewstage($ids = null )
    {
        $row = $this -> stage -> get($ids);
        $this ->assign('row',$row);
        return $this->view->fetch();  
    }

    /**
     * [delstage description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function delstage($ids = null)
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> stage -> find($ids);

        if(!$row)
            $this->error('记录不存在');
        $row->delete();
        $this->success();
    }

    /**
     * [addstage_admin description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function addstage_admin($ids = null)
    {
        $row = $this -> model -> get($ids);
        $row_stage = $this->stage-> where(['project_id'=>$ids])->order('id desc')->find();
        if(empty($row_stage))
        {
            $this -> error('请先添加项目阶段');
        }
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            if(isset($data['progress_status_id'])){
                $data['progress_status_name'] = Config::get('app.project_status')[$data['progress_status_id']];
            }
            if(isset($data['progress_status_time'])){
                $data['progress_status_time'] = strtotime($data['progress_status_time']);
            }
            $stage_list = $this->stage-> where(['project_id'=>$ids])->select();
            foreach($stage_list as $key => $value)
            {
                $stage = $this->stage-> get($value['id']);
                $stage->save($data);
            }
            // 同时把项目阶段更新到主表，带审核状态。
            if(isset($data['progress_status_id']))
            {
                $row->progress_status_id = $data['progress_status_id'];
                $row->progress_status_name = $data['progress_status_name'];    
                $row->progress_status_time = time();
                $row->save();                
            }
            $this -> success('添加成功');
        }    
        $this ->assign('row',$row);
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();      
    }

    /**
     * [addstage_admin description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function editstage_admin($ids = null)
    {
        $row = $this -> model -> get($ids);
        $row_stage = $this->stage-> where(['project_id'=>$ids])->order('id desc')->find();
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            if(isset($data['progress_status_id'])){
                $data['progress_status_name'] = Config::get('app.project_status')[$data['progress_status_id']];
                if(isset($data['progress_status_time']))
                    $data['progress_status_time'] = strtotime($data['progress_status_time']);
            }
            $stage_list = $this->stage-> where(['project_id'=>$ids])->select();
            foreach($stage_list as $key => $value)
            {
                $stage = $this->stage-> get($value['id']);
                $stage->save($data);
            }
            // 同时把项目阶段更新到主表，带审核状态。
            if(isset($data['progress_status_id']))
            {
                $row->progress_status_id = $data['progress_status_id'];
                $row->progress_status_name = $data['progress_status_name'];    
                $row->progress_status_time = time();
                $row->save();                
            }
            $this -> success('编辑成功');
        }    
        $this -> assign('row',$row);
        $this -> assign('row_stage',$row_stage);
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();      
    }

    public function adddemo($ids = null)
    {
        $row = $this -> model -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $row->allowField(true) -> save($data);               
            $this -> success('编辑成功');
        } 
        $this -> assign('row',$row);
        return $this->view->fetch();
    }
    /**
     * [progress description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function progress($ids = null)
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->where['project_id'] = $ids;
            // $this->where['status'] = 1;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->progress->with($this->relationtTable)
                ->where($where)
                ->where($this->where)
                ->order('id asc')
                ->count();
            $list = $this->progress->with($this->relationtTable)
                ->where($where)
                ->where($this->where)
                ->order('id asc')
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();
    }

    /**
     * [addprogress description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function addprogress($ids = null)
    {
        $row = $this -> model -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $data['report_id'] = $this-> auth ->id;
            $data['report_name'] = $this-> auth ->nickname;
            $data['progress_time'] = time();
            $data['status'] = -1 ;
            $ret = $this->progress-> save($data);
            if($ret)
                $this -> success('添加成功');
        }    
        $this ->assign('row',$row);
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();  
    }


    public function editprogress($ids = null)
    {
        $row = $this -> progress -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $data['report_id'] = $this-> auth ->id;
            $data['report_name'] = $this-> auth ->nickname;
            $data['progress_time'] = time();
            $data['status'] = -1 ;
            $ret = $row->allowField(true) -> save($data);
            if($ret)
                $this -> success('更新成功');
        } 
        $this ->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * [viewprogress description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function viewprogress($ids = null )
    {
        $row = $this -> progress -> get($ids);
        $this ->assign('row',$row);
        return $this->view->fetch();  
    }


    public function delprogress($ids = null)
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> progress -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->delete();
        $this->success();
    }

    /**
     * [plan description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function plan($ids = null)
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->Extend['project_id'] = $ids;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->plan->with($this->relationtTable)
                ->where($where)
                ->where($this->Extend)
                ->order('id asc')
                ->count();
            $list = $this->plan->with($this->relationtTable)
                ->where($where)
                ->where($this->Extend)
                ->order('id asc')
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();
    }


    /**
     * [addplan description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function addplan($ids = null)
    {
        $row = $this -> model -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $data['status'] = -1;
            $ret = $this->plan-> save($data);
            if($ret)
                return $this -> success('添加成功');
        }    
        $this ->assign('row',$row);
        $this -> assignConfig('ids',$ids);
        return $this->view->fetch();
    }

    public function editplan($ids = null)
    {
        $row = $this -> plan -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            if(isset($data['plan_status']))
            {
                if($data['plan_status']!=8)
                    $data['plan_other'] = '';
            }
            $ret = $row->allowField(true) -> save($data);
            if($ret)
                $this -> success('更新成功');
        } 
        $this ->assign('row',$row);
        return $this->view->fetch();
    }


    /**
     * [delplan description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function delplan($ids = null)
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> plan -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->delete();
        $this->success();
    }

    public function stand($ids = null)
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> plan -> find($ids);
        $data = [];
        $data['is_standard'] = 1;
        $ret = $row->allowField(true) -> save($data);
        $this->success(); 
    }

    /**
     * [del description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function del($ids = null)
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> model -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->is_delete = 1;
        $row->save();
        $this->success();
    }

    public function addcentralcontact($ids = null)
    {
        $row = $this -> model -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $ret = $this->centralcontact-> save($data);
            if($ret)
                return $this -> success('添加成功');
        }    
        $this ->assign('row',$row);
        $this -> assignConfig('ids',$ids);
        $this -> assign('centraloffices',getSelectList('centraloffice'));
        return $this->view->fetch();
    }

    public function editcentralcontact($ids = null)
    {
        $row = $this -> centralcontact -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $ret = $row->allowField(true) -> save($data);
            if($ret)
                $this -> success('更新成功');
        } 
        $this ->assign('row',$row);
        return $this->view->fetch();
    }
    public function delcentralcontact($ids = null)
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> centralcontact -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->delete();
        $this->success();
    }
    public function viewcentralcontact($ids = null )
    {
        $row = $this -> centralcontact -> get($ids);
        $this ->assign('row',$row);
        return $this->view->fetch();  
    }

    public function ajaxproject()
    {
        $name = $this -> request -> post('name');
        $isset = $this->model->where(['name'=>$name,'is_delete'=>0])->find();
        if(isset($isset))
        {
            return $this->success();
        }
    }

    public function export_base($data = [])
    {
        ini_set('memory_limit', '999M');
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where_delete = 'p.is_delete=0';
        if($data['action']=='export_discuss')
        {
            $where_delete = $where_delete.=' and p.progress_status_id=1';
            $xlsName = '在谈项目导出';
        }else if($data['action']=='export_new_land'){
            $where_delete = $where_delete.=' and p.carrier_id=1 and p.progress_status_id<9';
            $xlsName = '2021年签约新征地项目导出';
        }else if($data['action']=='export' || $data['action']=='export_centralcontact'){
            $where_delete = $where_delete.=' and p.progress_status_id<9';
            if($data['action']=='export'){
                $xlsName = '项目数据导出';
            }else{
                $xlsName = '中心接洽项目导出';
            }
        }else if($data['action']=='export_signed'){
            if($data['typeid']==1)
            {
                $where_delete = $where_delete.' and p.asset_type_id in(2,3) and p.progress_status_id<9';
            }else if($data['typeid']==2){
                $where_delete = $where_delete.' and p.asset_type_id=1 and p.progress_status_id<9';
            }else if($data['typeid']==3){
                $where_delete = $where_delete.' and p.progress_status_id<9';
            }else if($data['typeid']==4){
                $where_delete = $where_delete.' and p.progress_status_id<9';
            }
            $xlsName = '2021年签约项目导出';
        }
        $groupIds = $this->auth->getGroupIds();
        if(in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $where_delete .= " and p.chargedep_ids IN (".$chargedep_id.")";
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
        }
        $where_search = '';
        if($data['action']=='export_new_land'){
            $where_search='s.project_stage_id IN (4,5) and s.project_stage_time<'.strtotime('2021-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2021-01-01');
        }else if($data['action']=='export_centralcontact'){
            // $where_search = "c.leader_ids IN (".$data['leader'].") ";
            $where_search = "FIND_IN_SET(".$data['leader'].",c.leader_ids) ";
        }else if($data['action']=='signed'){
            if($data['typeid']==1)
            {
                $where_search = ' s.project_stage_id IN (4,5) and s.project_stage_time<'.strtotime('2021-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2021-01-01');
            }else if($data['typeid']==2){
                $where_search = ' s.project_stage_id IN (4,5) and  s.project_stage_time<'.strtotime('2021-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2021-01-01');
            }else if($data['typeid']==3){
                $where_search = ' s.project_stage_id =5 and s.project_stage_time<'.strtotime('2021-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2021-01-01');
            }else if($data['typeid']==4){
                $where_search = ' s.project_stage_id =4 and s.project_stage_time<'.strtotime('2021-12-31 23:59:59').' and s.project_stage_time>='.strtotime('2021-01-01');
            }
        }

        // 跟进时间是单独写的 filterextra
        $filter = $this->request->get("filterextra", '');
        $filter = (array)json_decode($filter, true);

        // 显示暂缓和终止
        if(!empty($filter['progress_statusid']))
        {
            $progress_statusid = $filter['progress_statusid'];
            if($progress_statusid==1)
                $where_search = "";
        }

        if(!empty($filter['project_stage_time']))
        {
            $project_stage_time = $filter['project_stage_time'];
            $dispatchTimeArr = explode(' - ',$project_stage_time);
            $dispatchtimeBetween = [strtotime(trim($dispatchTimeArr[0])),strtotime(trim($dispatchTimeArr[1]))];
            if(!empty($where_search))
                $where_search .= " and s.project_stage_time >= ".strtotime(trim($dispatchTimeArr[0]))." and s.project_stage_time <= ".strtotime(trim($dispatchTimeArr[1]))." and s.project_stage_time>0";
            else
                $where_search .= " s.project_stage_time >= ".strtotime(trim($dispatchTimeArr[0]))." and s.project_stage_time <=".strtotime(trim($dispatchTimeArr[1]))." and s.project_stage_time>0";
        }
        if(!empty($filter['project_stage_id']))
        {
            $project_stage_id = $filter['project_stage_id'];
            if($project_stage_id===1)
            {
                if(!empty($where_search))
                    $where_search .= " and p.progress_status_id = ".$project_stage_id;
                else
                    $where_search .= " p.progress_status_id = ".$project_stage_id;
            }else{
                if(!empty($where_search))
                    $where_search .= " and s.project_stage_id IN (".$project_stage_id.")";
                else
                    $where_search .= " s.project_stage_id IN (".$project_stage_id.")";
            }
        }

        if(!empty($filter['project_source_ids']))
        {
            $project_source_ids = $filter['project_source_ids'];
            $arr = explode(',', $project_source_ids);
            $str = "(";
            foreach ($arr as $key => $va){
                $str .= " FIND_IN_SET(".$va.",p.project_source_ids) or ";
            }
            $str = substr($str,0,-3);
            $str .= ")";
            $where_delete .= " and ".$str;
        }
        if(!empty($filter['trade_category_ids']))
        {
            $trade_category_ids = $filter['trade_category_ids'];
            $arr = explode(',', $trade_category_ids);
            $str = "(";
            foreach ($arr as $key => $va){
                $str .= " FIND_IN_SET(".$va.",p.trade_category_ids) or ";
            }
            $str = substr($str,0,-3);
            $str .= ")";
            $where_delete .= " and ".$str;
        }
        // 多选区领导接洽
        if(!empty($filter['leader_ids']))
        {
            $leader_ids = $filter['leader_ids'];
            $arr = explode(',', $leader_ids);
            $str = "(";
            foreach ($arr as $key => $va){
                $str .= " FIND_IN_SET(".$va.",c.leader_ids) or ";
            }
            $str = substr($str,0,-3);
            $str .= ")";
            $where_delete .= " and ".$str;
        } 
        // 多选接洽科室
        if(!empty($filter['centraloffice_id']))
        {
            $leader_ids = $filter['centraloffice_id'];
            $arr = explode(',', $leader_ids);
            $str = "(";
            foreach ($arr as $key => $va){
                $str .= " FIND_IN_SET(".$va.",c.centraloffice_id) or ";
            }
            $str = substr($str,0,-3);
            $str .= ")";
            $where_delete .= " and ".$str;
        }
        if(!empty($filter['contact_typeid']))
        {
            $contact_typeid = $filter['contact_typeid'];
            $where_delete .= " and c.contact_typeid = ".$contact_typeid;
        } 
        //接洽时间
        if(!empty($filter['receive_time']))
        {
            $receive_time = $filter['receive_time'];
            $dispatchTimeArr = explode(' - ',$receive_time);
            $dispatchtimeBetween = [strtotime(trim($dispatchTimeArr[0])),strtotime(trim($dispatchTimeArr[1]))];
            
            if(!empty($where_search))
                $where_search .= " and c.receive_time >= ".strtotime(trim($dispatchTimeArr[0]))." and c.receive_time <=".strtotime(trim($dispatchTimeArr[1]))." and c.receive_time>0";
            else
                $where_search .= " c.receive_time >= ".strtotime(trim($dispatchTimeArr[0]))." and c.receive_time <=".strtotime(trim($dispatchTimeArr[1]))." and c.receive_time>0";

        }
        // 投资方名称
        if(!empty($filter['investment_name']))
        {
            $investment_name = $filter['investment_name'];
            $str = " i.investment_name LIKE '%".$investment_name."%'";
            $where_delete .= " and ".$str;
        }

        // 投资方地区
        if(!empty($filter['investment_area']))
        {
            $investment_area = $filter['investment_area'];
            $str = " i.investment_area LIKE '%".$investment_area."%'";
            $where_delete .= " and ".$str;
        }

        // // 投资方国别
        if(!empty($filter['investment_country']))
        {
            $investment_country = $filter['investment_country'];
            $str = " i.investment_code = '".$investment_country."'";
            $where_delete .= " and ".$str;
        }        
        // 投资方性质
        if(!empty($filter['investment_attribute_ids']))
        {
            $investment_attribute_ids = $filter['investment_attribute_ids'];
            $arr = explode(',', $investment_attribute_ids);
            $str = "(";
            foreach ($arr as $key => $va){
                $str .= " FIND_IN_SET(".$va.",i.investment_attribute_ids) or ";
            }
            $str = substr($str,0,-3);
            $str .= ")";
            $where_delete .= " and ".$str;
        }
        $list = $this->model->alias('p')
            ->join('project_stage s','p.id=s.project_id','left')
            ->join('project_centralcontact c','p.id=c.project_id','left')
            ->join('project_investment i','p.id=i.project_id','left')
            ->join('chargedep g','p.chargedep_ids=g.id','left')
            ->field('p.*,s.project_id,s.project_stage_time,c.leader_ids,c.leader_names,c.receive_time,c.receive_time_desc,c.contact_typeid')
            ->where($where)
            ->where($where_search)
            ->where($where_delete)
            ->where($this->whereExtend)
            ->order('g.weigh asc')
            ->group('p.name')
            ->select();
            // echo $this->model->getLastSql();
            // exit();
        if(!empty($list)&&is_array($list))
        {   
            foreach ($list as $k => $val)
            {
                // 投资方
                $investment_name = '';
                $investment_area = '';
                $investment_country = '';
                $investment_attribute_names = '';
                $invest_list = $this->investment->where(['project_id'=>$val['id']])->order('id')->select();
                if(!empty($invest_list)&&is_array($invest_list))
                {
                    foreach ($invest_list as $ke => $v1) 
                    {
                        $investment_name .= $v1['investment_name']?$v1['investment_name'].' ':"";
                        $investment_area .= $v1['investment_area']?$v1['investment_area'].' ':"";
                        $investment_country .= $v1['investment_country']?$v1['investment_country'].' ':"";
                        $investment_attribute_names .= $v1['investment_attribute_names']?$v1['investment_attribute_names'].' ':""; 
                    }
                }
                $list[$k]['investment_name'] = $investment_name;
                $list[$k]['investment_area'] = $investment_area;
                $list[$k]['investment_country'] = $investment_country;
                $list[$k]['investment_attribute_names'] = $investment_attribute_names;

                // 协办单位联系
                $assist_name = '';                
                $contact_list = $this->contacts->where(['project_id'=>$val['id']])->order('id')->select();
                if(!empty($contact_list)&&is_array($contact_list))
                {
                    foreach ($contact_list as $ke => $v2) 
                    {
                        $assist_name .= $v2['assist_name'].','.$v2['assist_duty'].','.$v2['assist_nickname'].' ';
                    }
                }
                $list[$k]['assist_name'] = $assist_name;


                // 项目阶段
                $year = '';
                $zaitan = '';
                $kuangjia = '';
                $zhengshi = '';
                $zhuce = '';
                $zhuce_name = '';
                $zhunru = '';
                $nadi = '';
                $kaigong = '';
                $yunying = '';

                $stage_list = $this->stage->where(['project_id'=>$val['id']])->order('id')->select();
                if(!empty($stage_list)&&is_array($stage_list))
                {
                    foreach ($stage_list as $ke => $v3) 
                    {   
                        if($v3['year']>0 && !strstr($year,$v3['year'])){

                            $year .= $v3['year'].";"; 
                        }

                        switch ($v3['project_stage_id']) {
                            case '1':
                                $zaitan .= isset($v3['project_stage_time'])?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;

                            case '3': //准入
                                $zhunru .= isset($v3['project_stage_time']) ?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;

                            case '4': //框架协议
                                $kuangjia .= isset($v3['project_stage_time'])?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;
                            case '5': //正式协议
                                $zhengshi .= isset($v3['project_stage_time'])?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;

                            case '6': //注册
                                $zhuce .= isset($v3['project_stage_time']) ? date('Y-m-d',$v3['project_stage_time'])." ":"";
                                $zhuce_name = isset($v3['register_name']) ? $v3['register_name']:"";
                                break;

                            case '7': //拿地
                                $nadi .= isset($v3['project_stage_time']) ?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;

                            case '8'://开工
                                $kaigong .= isset($v3['project_stage_time'])?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;

                            case '9'://暂缓
                                break;

                            case '10'://终止
                                break;

                            default: //运营 progress_status_id 为2
                                $yunying = isset($v3['project_stage_time']) ?date('Y-m-d',$v3['project_stage_time'])." ":"";
                                break;
                        }
                    }
                }
                $list[$k]['year'] = $year;
                $list[$k]['kuangjia'] = $kuangjia;
                $list[$k]['zhengshi'] = $zhengshi?$zhengshi:'-';
                $list[$k]['zhuce'] = $zhuce?$zhuce:'-';
                $list[$k]['zhuce_name'] = $zhuce_name;
                $list[$k]['zhunru'] = $zhunru?$zhunru:'-';
                $list[$k]['nadi'] = $nadi?$nadi:'-';
                $list[$k]['kaigong'] = $kaigong?$kaigong:'-';
                $list[$k]['yunying'] = $yunying?$yunying:'-';

                // 项目进展详情
                $progress_list = $this->progress->where(['project_id'=>$val['id']])->order('id desc')->find();
                $list[$k]['content'] = $progress_list['content']?$progress_list['content']:"";
                $list[$k]['problem'] = $progress_list['problem']?$progress_list['problem']:"";
                $list[$k]['next_measure'] = $progress_list['next_measure']?$progress_list['next_measure']:"";

                // 产业领域
                if($val['industry_realm_id']==14)
                {
                    $list[$k]['industry_realmname'] = $val['industry_realm_other'];
                }else{
                    $list[$k]['industry_realmname'] = $val['industry_realm_name'];
                }

                // 五大产业
                if($val['five_industry_id']==6)
                {
                    $list[$k]['five_industryname'] = $val['five_industry_other'];
                }else{
                    $list[$k]['five_industryname'] = $val['five_industry_name'];
                }

                switch ($val['status']) {
                    case '-1':
                        $list[$k]['status_text'] = '待提交';
                        break;
                    case '0':
                        $list[$k]['status_text'] = '待审核';
                        break;
                    case '1':
                        $list[$k]['status_text'] = '已更新';
                        break;
                    case '2':
                        $list[$k]['status_text'] = '已驳回';
                        break;
                    default:
                        $list[$k]['status_text'] = '未更新';
                        break;
                }

                // 接洽记录
                $leadernames = '';
                $receive_time = '';
                $contact_typename = '';
                $contact_city = '';
                $centraloffice_name = '';

                $central_list = $this->centralcontact->where(['project_id'=>$val['id']])->order('leader_ids asc')->select();
                if(!empty($central_list)&&is_array($central_list))
                {
                    foreach ($central_list as $ke => $vv) 
                    {
                        if(!empty($vv['leader_names']))
                        {   
                            $arr_str = '';
                            $leader_arr = explode(',',$vv['leader_names']);
                            foreach ($leader_arr as $key => $v)
                            {   
                                if(!strstr($leadernames, $v))
                                    $arr_str.= $v;
                            }
                            $leadernames .= $arr_str.';';
                        }
                        $receive_time .= $vv['receive_time']>0?date('Y-m-d',$vv['receive_time']).';':"";

                        if(!empty($vv['contact_typename']) && !strstr($contact_typename, $vv['contact_typename']))
                            $contact_typename .= $vv['contact_typename'].';';
                        
                        if(!empty($vv['contact_city']) && !strstr($contact_city, $vv['contact_city']))
                            $contact_city .= $vv['contact_city'].';';
                        
                        if(!empty($vv['centraloffice_name']) && !strstr($centraloffice_name, $vv['centraloffice_name']))
                            $centraloffice_name .= $vv['centraloffice_name'].';';
                        
                    }
                }

                $list[$k]['leadernames'] = $leadernames;
                $list[$k]['receive_time'] = $receive_time;
                $list[$k]['contact_typename'] = $contact_typename;
                $list[$k]['contact_city'] = $contact_city;
                $list[$k]['centraloffice_name'] = $centraloffice_name;

                $central_info = $this->centralcontact->where(['project_id'=>$val['id']])->order('leader_ids desc')->find();
                $list[$k]['content'] = $central_info['content'] ? $central_info['content'] :'';
            }
        }
        

        $xlsCell = array('序号','状态','年度','项目名称','项目简介','主责部门','协办部门','建设地址','落户街道','分管区领导','投资类别','产业类别','产业领域','五大产业','行业类别','项目类别','载体类别','载体面积','总投资(亿元)','内资(亿元)','外资(万美元)','投资方名称','投资方国别','投资方地区','投资方性质','主责单位联系人','协办单位联系人','招商促进联系人','签订框架协议时间','签订正式协议时间','注册时间','注册公司名称','准入时间','拿地时间','开工时间','运营时间','项目当前阶段','项目进展情况','存在问题','下一步措施','接洽领导','接洽时间','接洽类别','接洽地点','中心陪同科室','项目备注','会谈内容');

        $xlsDataReal = [];
        foreach ($list as $key => $value) {
            $xlsDataReal[] = [
                ++$key,
                $value['status_text'],
                $value['year'],
                $value['name'],
                $value['summary'],
                $value['chargedep_names'],
                $value['assist_names'],
                $value['build_address'],
                $value['settle_street_names'],
                $value['branch_leader_name'],
                $value['asset_type_name'],
                $value['industry_category_name'],
                $value['industry_realmname'],//产业领域
                $value['five_industryname'],//五大产业
                $value['trade_category_names'],
                $value['project_source_names'],
                $value['carrier_name'],
                $value['carrier_id_relation'].$value['carrier_id_relation_unit'],
                $value['investment_total'],
                $value['domestic_capital'],
                $value['foreign_capital'],
                $value['investment_name'],
                $value['investment_country'],
                $value['investment_area'],
                $value['investment_attribute_names'],
                $value['organizer_depart'].",".$value['organizer_duty'].",".$value['organizer_name'],
                $value['assist_name'],
                $value['socialized_department'].",".$value['socialized_name'],
                $value['kuangjia'],
                $value['zhengshi'],
                $value['zhuce'],
                $value['zhuce_name'],
                $value['zhunru'],
                $value['nadi'],
                $value['kaigong'],
                $value['yunying'],
                $value['progress_status_name'],
                $value['content'],
                $value['problem'],
                $value['next_measure'],
                $value['leadernames'],
                $value['receive_time'],
                $value['contact_typename'],
                $value['contact_city'],
                $value['centraloffice_name'],
                $value['project_demo'],
                $value['content'],
            ];
        }
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);
        exit();
    }
    public function export_discuss()
    {
        $data = [
            'action'=>'export_discuss',
            'leader'=>0,
            'typeid'=>0
        ];
        return self::export_base($data);
    }

    public function export_new_land()
    {
        $data = [
            'action'=>'export_new_land',
            'leader'=>0,
            'typeid'=>0
        ];
        return self::export_base($data);
    }
    public function export_centralcontact($leader = NULL)
    {
        $data = [
            'action'=>'export_centralcontact',
            'leader'=>$leader,
            'typeid'=>0
        ];
        return self::export_base($data);
    }
    public function export_signed($typeid = NULL)
    {
        $data = [
            'action'=>'export_signed',
            'leader'=>0,
            'typeid'=>$typeid
        ];
        return self::export_base($data);
    }
    public function export()
    {
        $data = [
            'action'=>'export',
            'leader'=>0,
            'typeid'=>0
        ];
        return self::export_base($data);
    }
    protected function anaData($where_str = '') {
        $nan = $this -> model -> query("select count(*) as 'projectcount',
sum(IF(investment_total > 0,investment_total,0)) as 'investment_total',
SUM(IF(investment_total >= 1,1,0)) as 'over1count',
SUM(IF(investment_total >= 1,investment_total,0)) as 'over1amount',
SUM(IF(investment_total >= 5,1,0)) as 'over5count',
SUM(IF(investment_total >= 5,investment_total,0)) as 'over5amount',
SUM(IF(investment_total >= 50,1,0)) as 'over50count',
SUM(IF(investment_total >= 50,investment_total,0)) as 'over50amount',
SUM(IF(investment_total >= 100,1,0)) as 'over100count',
SUM(IF(investment_total >= 100,investment_total,0)) as 'over100amount',
sum(IF(FIND_IN_SET(1,chargedep_ids),1,0)) as 'chengyangcount',
sum(IF(FIND_IN_SET(1,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'chengyangamount',
sum(IF(FIND_IN_SET(2,chargedep_ids),1,0)) as 'liutingcount',
sum(IF(FIND_IN_SET(2,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'liutingamount',
sum(IF(FIND_IN_SET(3,chargedep_ids),1,0)) as 'xiazhuangcount',
sum(IF(FIND_IN_SET(3,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'xiazhuangamount',
sum(IF(FIND_IN_SET(4,chargedep_ids),1,0)) as 'xifuzhencount',
sum(IF(FIND_IN_SET(4,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'xifuzhenamount',
sum(IF(FIND_IN_SET(5,chargedep_ids),1,0)) as 'jihongtancount',
sum(IF(FIND_IN_SET(5,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'jihongtanamount',
sum(IF(FIND_IN_SET(6,chargedep_ids),1,0)) as 'shangmacount',
sum(IF(FIND_IN_SET(6,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'shangmaamount',
sum(IF(FIND_IN_SET(7,chargedep_ids),1,0)) as 'hetaocount',
sum(IF(FIND_IN_SET(7,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'hetaoamount',
sum(IF(FIND_IN_SET(8,chargedep_ids),1,0)) as 'hongdaocount',
sum(IF(FIND_IN_SET(8,chargedep_ids),investment_total,0)) as 'hongdaoamount',
sum(IF(FIND_IN_SET(13,chargedep_ids),1,0)) as 'guidaocount',
sum(IF(FIND_IN_SET(13,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'guidaoamount',
sum(IF(FIND_IN_SET(14,chargedep_ids),1,0)) as 'jinrongcount',
sum(IF(FIND_IN_SET(14,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'jinrongamount',
sum(IF(FIND_IN_SET(15,chargedep_ids),1,0)) as 'dashujucount',
sum(IF(FIND_IN_SET(15,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'dashujuamount',
sum(IF(FIND_IN_SET(29,chargedep_ids),1,0)) as 'dongchecount',
sum(IF(FIND_IN_SET(29,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'dongcheamount',
sum(IF(FIND_IN_SET(30,chargedep_ids),1,0)) as 'ygctcount',
sum(IF(FIND_IN_SET(30,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'ygctamount',

sum(IF(FIND_IN_SET(31,chargedep_ids),1,0)) as 'zonghecount',
sum(IF(FIND_IN_SET(31,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'zongheamount',
sum(IF(FIND_IN_SET(34,chargedep_ids),1,0)) as 'huanhaicount',
sum(IF(FIND_IN_SET(34,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'huanhaiamount',
sum(IF(FIND_IN_SET(26,chargedep_ids),1,0)) as 'shizhengcount',
sum(IF(FIND_IN_SET(26,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'shizhengamount',
sum(IF(FIND_IN_SET(27,chargedep_ids),1,0)) as 'chengshicount',
sum(IF(FIND_IN_SET(27,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'chengshiamount',
sum(IF(FIND_IN_SET(28,chargedep_ids),1,0)) as 'kaifacount',
sum(IF(FIND_IN_SET(28,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'kaifaamount',
sum(IF(FIND_IN_SET(29,chargedep_ids),1,0)) as 'dongchecount',
sum(IF(FIND_IN_SET(29,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'dongcheamount',
sum(IF(FIND_IN_SET(30,chargedep_ids),1,0)) as 'chuangxincount',
sum(IF(FIND_IN_SET(30,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'chuangxinamount',
sum(IF(FIND_IN_SET(45,chargedep_ids),1,0)) as 'nongyecount',
sum(IF(FIND_IN_SET(45,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'nongyeamount',
sum(IF(FIND_IN_SET(50,chargedep_ids),1,0)) as 'konggucount',
sum(IF(FIND_IN_SET(50,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'kongguamount',
sum(IF(FIND_IN_SET(51,chargedep_ids),1,0)) as 'xinchengcount',
sum(IF(FIND_IN_SET(51,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'xinchengamount',
sum(IF(FIND_IN_SET(52,chargedep_ids),1,0)) as 'hongjiancount',
sum(IF(FIND_IN_SET(52,chargedep_ids),IF(investment_total > 0,investment_total,0),0)) as 'hongjianamount',

sum(case five_industry_id when 1 then 1 else 0 end) as 'gaoduancount',
sum(case five_industry_id when 2 then 1 else 0 end) as 'xinnengyuancount',
sum(case five_industry_id when 3 then 1 else 0 end) as 'xinyidaicount',
sum(case five_industry_id when 4 then 1 else 0 end) as 'shengwucount',
sum(case five_industry_id when 5 then 1 else 0 end) as 'xiandaicount',
sum(case five_industry_id when 6 then 1 else 0 end) as 'qitacount',

sum(case industry_category_id when 6 then 1 else 0 end) as 'nongyecount',
sum(case industry_category_id when 7 then 1 else 0 end) as 'zhizaoyecount',
sum(case industry_category_id when 8 then 1 else 0 end) as 'jianzhuyecount',
sum(case industry_category_id when 9 then 1 else 0 end) as 'fuwuyecount',
sum(case industry_category_id when 10 then 1 else 0 end) as 'fangdichancount',
sum(case industry_category_id when 11 then 1 else 0 end) as 'ronghecount',
sum(case industry_category_id when 12 then 1 else 0 end) as 'keyancount',

sum(IF(FIND_IN_SET(6,trade_category_ids),1,0)) as 'xinjijiancount',
sum(IF(FIND_IN_SET(6,trade_category_ids),IF(investment_total > 0,investment_total,0),0)) as 'xinjijianamount',

sum(IF(FIND_IN_SET(7,trade_category_ids),1,0)) as 'gongyecount',
sum(IF(FIND_IN_SET(7,trade_category_ids),IF(investment_total > 0,investment_total,0),0)) as 'gongyeamount',

sum(IF(FIND_IN_SET(8,trade_category_ids),1,0)) as 'zongbucount',
sum(IF(FIND_IN_SET(8,trade_category_ids),IF(investment_total > 0,investment_total,0),0)) as 'zongbuamount',

sum(IF(FIND_IN_SET(9,trade_category_ids),1,0)) as 'sixincount',
sum(IF(FIND_IN_SET(9,trade_category_ids),IF(investment_total > 0,investment_total,0),0)) as 'sixinamount'

from ".$this->project_tablename." WHERE is_delete =0 and progress_status_id<9 and id in( select project_id from nsig_project_stage WHERE project_stage_id in(4,5) and project_stage_time>=".strtotime(date("Y")."-01-01").")");
        $nan = $nan[0];
       
        //单独取投资公司
//         $touzi_ids='26,27,28,29,30,45,50,51,52';
//         $touzi_nan = $this -> model -> query("select count(*) as touzicount,SUM(investment_total) AS 'touziamount' 
// from ".$this->project_tablename." WHERE chargedep_ids IN (".$touzi_ids.") and is_delete =0 and progress_status_id<9 and id in( select project_id from nsig_project_stage WHERE project_stage_id in(4,5) and project_stage_time>=".strtotime("2021-01-01").")" );
//         $touzi_nan = $touzi_nan[0];

        //单独取区直部门
        $chargedep_ids='10,11,12,14,15,16,17,18,19,20,21,22,23,24,25,32,33,36,37,38,39,40,42,44,45,46,47,48,49,53,54,55';
        $quzhi_nan = $this -> model -> query("select count(*) as quzhicount,SUM(investment_total) AS 'quzhiamount' 
from ".$this->project_tablename." WHERE chargedep_ids IN (".$chargedep_ids.") and is_delete =0 and progress_status_id<9 and id in( select project_id from nsig_project_stage WHERE project_stage_id in(4,5) and project_stage_time>=".strtotime(date("Y")."-01-01").")" );
        $quzhi_nan = $quzhi_nan[0];

        $str = "
        2022年截至目前，全区签约项目{$nan['projectcount']}个，计划总投资{$nan['investment_total']}亿元。<br />
按投资额划分：过亿元项目{$nan['over1count']}个{$nan['over1amount']}亿元，5亿元以上项目{$nan['over5count']}个{$nan['over5amount']}亿元，50亿元以上项目{$nan['over50count']}个{$nan['over50amount']}亿元，100亿元以上项目{$nan['over100count']}个{$nan['over100amount']}亿元。<br />";
    $str .="按街道划分：";
    if($nan['chengyangcount'] > 0)
        $str .= "城阳街道{$nan['chengyangcount']}个{$nan['chengyangamount']}亿元，";
    if($nan['liutingcount'] > 0)
        $str .= "流亭街道{$nan['liutingcount']}个{$nan['liutingamount']}亿元，";
    if($nan['xiazhuangcount'] > 0)
        $str .= "夏庄街道{$nan['xiazhuangcount']}个{$nan['xiazhuangamount']}亿元，";
    if($nan['xifuzhencount'] > 0)
        $str .= "惜福镇街道{$nan['xifuzhencount']}个{$nan['xifuzhenamount']}亿元，";
    if($nan['jihongtancount'] > 0)
        $str .= "棘洪滩街道{$nan['jihongtancount']}个{$nan['jihongtanamount']}亿元，";
    if($nan['shangmacount'] > 0)
        $str .= "上马街道{$nan['shangmacount']}个{$nan['shangmaamount']}亿元，";
    if($nan['hongdaocount'] > 0)
        $str .= "红岛街道{$nan['hongdaocount']}个{$nan['hongdaoamount']}亿元，";
    if($nan['hetaocount'] > 0)
        $str .= "河套街道{$nan['hetaocount']}个{$nan['hetaoamount']}亿元，";
    if($nan['guidaocount'] > 0)
        $str .= "轨道交通产业示范区{$nan['guidaocount']}个{$nan['guidaoamount']}亿元，";
    if($nan['zonghecount'] > 0)
        $str .= "胶州湾综合保税区{$nan['zonghecount']}个{$nan['zongheamount']}亿元，";
    if($nan['huanhaicount'] > 0)
        $str .= "环海经济开发区{$nan['huanhaicount']}个{$nan['huanhaiamount']}亿元，";
    // if($touzi_nan['touzicount'] > 0)
    //     $str .= "投资公司{$touzi_nan['touzicount']}个{$touzi_nan['touziamount']}亿元，";
    //     
    if($nan['shizhengcount'] > 0)
        $str .= "城阳市政投资集团{$nan['shizhengcount']}个{$nan['shizhengamount']}亿元，";
    if($nan['chengshicount'] > 0)
        $str .= "城阳城市发展集团有限公司{$nan['chengshicount']}个{$nan['chengshiamount']}亿元，";
    if($nan['kaifacount'] > 0)
        $str .= "城阳开发投资集团有限公司{$nan['kaifacount']}个{$nan['kaifaamount']}亿元，";
    if($nan['dongchecount'] > 0)
        $str .= "动车小镇投资公司{$nan['dongchecount']}个{$nan['dongcheamount']}亿元，";
    if($nan['chuangxincount'] > 0)
        $str .= "城阳阳光创新投资有限公司{$nan['chuangxincount']}个{$nan['chuangxinamount']}亿元，";
    if($nan['nongyecount'] > 0)
        $str .= "阳光农业发展投资有限公司{$nan['nongyecount']}个{$nan['nongyeamount']}亿元，";
    if($nan['konggucount'] > 0)
        $str .= "城阳区阳光城阳控股集团有限公司{$nan['konggucount']}个{$nan['kongguamount']}亿元，";
    if($nan['xinchengcount'] > 0)
        $str .= "青岛环海新城投资有限公司{$nan['xinchengcount']}个{$nan['xinchengamount']}亿元，";
    if($nan['hongjiancount'] > 0)
        $str .= "青岛红建投资有限公司{$nan['hongjiancount']}个{$nan['hongjianamount']}亿元，";

    if($quzhi_nan['quzhicount'] > 0)
        $str .= "区直部门{$quzhi_nan['quzhicount']}个{$quzhi_nan['quzhiamount']}亿元，";


    
    $str .="<br>";
    $str .="按五大产业划分：高端装备{$nan['gaoduancount']}个，新一代信息技术{$nan['xinyidaicount']}个，新材料新能源{$nan['xinnengyuancount']}个，生物医药{$nan['shengwucount']}个，现代服务业{$nan['xiandaicount']}个,其他{$nan['qitacount']}个。";
    $str .="<br>";
    $str .="按产业类别划分：农业{$nan['nongyecount']}个，制造业{$nan['zhizaoyecount']}个，建筑业{$nan['jianzhuyecount']}个，服务业{$nan['fuwuyecount']}个，房地产{$nan['fangdichancount']}个,产城融合{$nan['ronghecount']}个,学校及科研院所{$nan['keyancount']}个。";
    $str .="<br>";
    $str .="新基建项目{$nan['xinjijiancount']}个{$nan['xinjijianamount']}亿元，工业互联网{$nan['gongyecount']}个{$nan['gongyeamount']}亿元,总部项目{$nan['zongbucount']}个{$nan['zongbuamount']}亿元,四新项目{$nan['sixincount']}个{$nan['sixinamount']}亿元。<br />";
        return $str;
    }
    protected function addCheck($ids,$field='',$data = []){

        $row = $this->model -> get($ids);
        $logData = [
            'project_id' => $row->id,
            'project_name'  => $row ->name,
            'operate_field' => $field,
            'old_content' => $row->$field,
            'new_content' => $data,
            'operator_id'   => $this -> auth -> id,
            'operator_nickname' => $this -> auth -> nickname,
        ];
        \app\admin\model\ProjectCheck::create($logData);
    }

}